Function CountColor(rColor As Range, rSumRange As Range)
Dim rCell As Range
Dim iCol As Integer
Dim vResult As Integer
iCol = rColor.Interior.ColorIndex
For Each rCell In rSumRange
If rCell.Interior.ColorIndex = iCol Then
vResult = 1
Else
vResult = 0
End If
Next rCell
CountColor = vResult
End Function
我尝试输入 "=CountColor(A1, A2)"
,但我总是收到错误"Sub or function not defined"
这是为什么?我已经坚持了几个小时。
答案 0 :(得分:1)
我无法重现您遇到的错误。
如果您使用代码,结果将不准确,例如:
=CountColor(A1,B1:B20)
只会给你1或0的结果,因为你没有将结果加在一起。
如果你只是比较内部颜色,你真的不需要使用interior.colorindex
,只有interior.color
应该有效,所以我改变了iCol as string
else
。
我还在代码中添加了Application.volatile
,因此它将计算工作表的计算时间。
Function CountColor(rColor As Range, rSumRange As Range)
Dim rCell As Range
Dim iCol As String
Dim vResult As Integer
iCol = rColor.Interior.Color
Application.Volatile
For Each rCell In rSumRange
If rCell.Interior.Color = iCol Then
vResult = 1 + vResult
' Else
' vResult = 0
End If
Next rCell
CountColor = vResult
End Function