简体   繁体   English

"Excel VBA 用户定义函数,用于计算具有条件格式的单元格"

[英]Excel VBA User Defined Function that counts cells with conditional formatting

I am trying to write a UDF that counts the number of cells that have conditional formatting.我正在尝试编写一个 UDF 来计算具有条件格式的单元格的数量。 I wrote the following sub that works like a charm:我写了以下子程序,它就像一个魅力:

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

and I tried to convert it to a UDF with the following code:我尝试使用以下代码将其转换为 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     

However when I try the UDF i get a #VALUE!但是,当我尝试 UDF 时,我得到了 #VALUE! returned.回。 I'm really not sure why and any help would be much appreciated.我真的不知道为什么,任何帮助将不胜感激。

You can work around the inability to access DisplayFormat in a UDF using Evaluate您可以使用Evaluate解决无法访问 UDF 中的DisplayFormat

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM