Microsoft VBA功能可对条件格式化的彩色单元格进行计数

时间:2018-12-27 16:33:10

标签: excel vba excel-vba

嗨,我发现一个宏可以成功计算条件格式的彩色单元格,但是当我尝试将其更改为函数时,它不起作用-我在这里读到它可能是因为.DisplayFormat.Interior.Color没有无法使用功能-有人知道解决方法吗?

'Variable declaration
Dim lColorCounter2 As Long
Dim rngCell2 As Range
'loop throughout each cell in the range
For Each rngCell2 In Selection
    'Checking Amber color
    If Cells(rngCell2.Row, rngCell2.Column).DisplayFormat.Interior.Color = RGB(255, 192, 0) Then
        lColorCounter2 = lColorCounter2 + 1
    End If
Next
MsgBox "Green =" & lColorCounter2    

理想情况下,我希望函数具有两个参数,第一个参数是要搜索颜色的单元格范围,第二个参数是要查找颜色的单元格。

1 个答案:

答案 0 :(得分:0)

请记住:

  1. RGB(255,192,0)不是绿色,而是接近橙色。
  2. 更改要循环的范围-rng(现在rng等于 Sheet1.Range(“ A1:A20”)

尝试:

Option Explicit

Public Function Color(ByVal rng As Range)

    Dim Counter As Long
    Dim Cell As Range

    For Each Cell In rng
        'Checking Amber color
        If Cells(Cell.Row, Cell.Column).DisplayFormat.Interior.Color = RGB(255, 192, 0) Then
            Counter = Counter + 1
        End If
    Next

    MsgBox "Orange=" & Counter

End Function

Sub test()

    Dim rng As Range

    Set rng = Sheet1.Range("A1:A20")

    Call Color(rng)

End Sub