function:错误子或function未定义

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"为什么这是? 我一直坚持这个小时。

我无法重现您遇到的错误。

如果您使用代码,结果将不准确,例如: =CountColor(A1,B1:B20)只会给您1或0的结果,因为您没有将结果相加。

如果你只是比较内部的颜色,你不需要使用interior.colorindex ,只是interior.color应该工作,所以我改变了iCol as string

else在你的if语句中不需要。

我还在代码中添加了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