簡體   English   中英

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 的單元格中,我收到錯誤消息“值”。 我將非常感謝您的幫助。

我更正了我的代碼,但它沒有完全回答您的問題,因為它不包括條件格式。

更正的代碼:

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

但是,如果此解決方案不能滿足您的要求,我有一個不同的 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM