使用条件格式计算单元格的 Excel VBA 用户定义函数

DBA*_*642 1 excel vba

我正在尝试编写一个 UDF 来计算具有条件格式的单元格的数量。我写了以下子,就像一个魅力:

Sub SumCountByConditionalFormat()
Dim cellrngi As Range
Dim cntresi As Long

cntresi = 0

Set cellrngi = Sheets("Sheet3").Range("I2:I81")

For Each i In cellrngi
    If i.DisplayFormat.Interior.Color <> 16777215 Then
    cntresi = cntresi + 1
    End If
Next i
end sub
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下代码将其转换为 UDF:

Function CountCellsByColor1(rData As Range) As Long
Dim cntRes As Long

Application.Volatile
cntRes = 0
For Each cell In rData
    If cell.DisplayFormat.Interior.Color <> 16777215 Then
        cntRes = cntRes + 1
    End If
Next cell

CountCellsByColor1 = cntRes
End Function     
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试 UDF 时,我得到一个 #VALUE!回来。我真的不知道为什么,任何帮助将不胜感激。

Tim*_*ams 5

您可以使用以下方法解决无法DisplayFormat在 UDF 中访问的问题Evaluate

Function DFColor(c As Range)
    DFColor = c.DisplayFormat.Interior.Color
End Function


Function CountCellsByColor1(rData As Range) As Long
    Dim cntRes As Long, clr As Long, cell As Range
    cntRes = 0
    For Each cell In rData.Cells
        'Evaluate the formula string in the context of the
        '  worksheet hosting rData
        clr = rData.Parent.Evaluate("DFColor(" & cell.Address() & ")")
        If clr <> 16777215 Then
            cntRes = cntRes + 1
        End If
    Next cell
    CountCellsByColor1 = cntRes
End Function
Run Code Online (Sandbox Code Playgroud)