Vba 计数范围内具有特定颜色的单元格,由条件格式着色

Vba count cells in a range with a specific color, colored by the Conditional Formatting

我尝试对范围内具有特定颜色的所有单元格进行计数。在我的例子中,颜色是绿色 (ColorIndex: 43)。单元格的颜色由条件格式决定。

我的代码到现在如下:

Function Count_color(range_data As Range, Farbe As Integer) As Integer
    Dim datax As Range
    Dim index As Integer
    For Each datax In range_data
        index = datax.DisplayFormat.Interior.ColorIndex
        If index = Farbe Then
            Count_color = Count_color + 1
        End If
    Next datax
End Function

在我应用函数的单元格中,我收到错误消息“值”。 非常感谢您的帮助。

我更正了我的代码,但它没有完全回答你的问题,因为它不包括条件格式。

更正后的代码:

Function my_Count_Color(Arg1 As Range, Farbe As Integer) As Integer
    Dim elem As Variant
    For Each elem In Arg1
        If elem.Interior.ColorIndex = Farbe Then
        my_Count_Color = my_Count_Color + 1
        End If
    Next elem
    
End Function

要检查,请使用此公式:

Function GetColor(R As Range) As Integer
    GetColor = R.Interior.ColorIndex
End Function

但是,如果这个解决方案不能让您满意,我有一个不同的功能建议给您,应该能满足您的期望。唯一发生的变化是从 ColorIndex 到 RGB。 ColorIndex = 43 = RGB (146,208,80) 对应的值。 我将它们作为可选代入公式中,或者更确切地说是 2。 现在你可以输入 My_Count_Color_2 = (G1: G10) 要么 My_Count_Color_2 = (G1: G10; 146; 208; 80)

这是我的代码:

Function my_Count_Color_2(rng As Range, Optional R As Integer = 146, Optional G As Integer = 208, Optional B As Integer = 80) As Integer
    Dim elem As Variant
        For Each elem In rng
                If (rng.Parent.Evaluate("DFColor(""" & elem.Address & """)") = RGB(R, G, B)) = True Then
                    my_Count_Color_2 = my_Count_Color_2 + 1
                End If
        Next elem
    
End Function

Public Function DFColor(addr)
    DFColor = Range(addr).DisplayFormat.Interior.Color
End Function