【问题标题】:Modify VBA To Account For Conditional Formatting修改 VBA 以考虑条件格式
【发布时间】:2016-08-06 07:18:28
【问题描述】:

我正在尝试在 Excel 2016 中使用类似 COUNTIF 的函数按背景颜色汇总一系列单元格... 3 种不同颜色(绿色、黄色、红色)代表 3 个不同的“状态”(第一个最大,第二大,第三大)。我设法通过使用此 VBA 编码使其工作:

Function Countcolour(rng As Range, colour As Range) As Long
 Dim c As Range
 Application.Volatile
 For Each c In rng
     If c.Interior.ColorIndex = colour.Interior.ColorIndex Then
         Countcolour = Countcolour + 1
     End If
 Next
 End Function

但是,此特定代码并未考虑条件格式。

例如,我尝试有条件地格式化一组数据,以突出显示其第一个最大值绿色、第二大黄色、第三大红色。我在另一个块中使用这个 VBA 函数来计算所有绿色高光。但是,由于条件格式,它不会拾取单元格的背景颜色。

我确定我遗漏了一些明显的东西......我觉得If 条件的第一部分应该是c.FormatCondition.Interior 的某种形式,但我尝试了主题的变体,但没有成功。

提前感谢您提供的任何帮助!

【问题讨论】:

标签: excel vba


【解决方案1】:

这是很多人尝试做的事情,包括我。

互联网上有一些有用的代码,例如http://www.cpearson.com/excel/CFColors.htm 但经过大量搜索后,我发现只有一个答案 get conditional formatted color with vba in excel 并且有效!

解决方法很简单:

你可以使用

.cells(1,1).displayformat.interior.color 

.cells(1,1).displayformat.interior.colorIndex

例子:

Function CountColor(ByRef rng As Range, ByRef color As Long) As Variant
    Dim total: total = 0
    If (Not (rng Is Nothing)) Then
        Dim element As Variant
        For Each element In rng
            total = total - (element.DisplayFormat.Interior.color = color) ' MINUS because TRUE evaluates to -1
        Next element
    End If
    CountColor = total
End Function

Sub test_countColors()
    With Sheet1
        Dim rng As Range
        Dim color As Long
        Dim total As Long
        Set rng = Range(.Cells(1, 1), .Cells(3500, 55))   ' Or anay other range
        color = 8438015                                   ' Or any other color
        total = CountColor(rng, color)  
        MsgBox "Total= " & total
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多