Excel VBA用户定义的函数,用于计算具有条件格式的单元格
我正在尝试编写一个UDF,用于计算具有条件格式的单元格数。我写了下面这篇文章,很有魅力:Excel VBA用户定义的函数,用于计算具有条件格式的单元格,excel,vba,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 <&
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
Sub-SumCountByConditionalFormat()
暗淡的cellrngi As范围
长得一样暗
cntresi=0
设置cellrngi=板材(“板材3”)。范围(“I2:I81”)
对于cellrngi中的每个i
如果i.DisplayFormat.Interior.Color 16777215,则
cntresi=cntresi+1
如果结束
接下来我
端接头
我尝试用以下代码将其转换为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
函数CountCellsByColor1(rData作为范围)的长度
暗淡的cntRes一样长
应用程序。挥发性
cntRes=0
对于rData中的每个单元格
如果cell.DisplayFormat.Interior.Color 16777215,则
cntRes=cntRes+1
如果结束
下一个细胞
CountCellsByColor1=cntRes
端函数
然而,当我尝试UDF时,我得到了一个#值!返回。我真的不知道为什么,任何帮助都将不胜感激。您可以使用
评估
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
函数DFColor(c作为范围)
DFColor=c.DisplayFormat.Interior.Color
端函数
函数CountCellsByColor1(rData作为范围)的长度
变暗cntRes为长,clr为长,单元格为范围
cntRes=0
对于rData.Cells中的每个单元格
'在
'托管rData的工作表
clr=rData.Parent.Evaluate(“DFColor(&cell.Address()&”))
如果是clr 16777215,则
cntRes=cntRes+1
如果结束
下一个细胞
CountCellsByColor1=cntRes
端函数
请参见@SJR谢谢!不幸的是,现在不是#价值!我得到了一个0。在测试函数时,仅从代码中删除DisplayFormat
就得到了正确的值。确保选择了正确的单元格,并使用F9
运行计算,以更新excel 2010中的单元格,并使用Power Query。您认为这可能是导致错误的原因吗?您可以在函数中始终使用CF条件。