#VALUE错误时返回平均或“”function的单元格

我有以下的VBA代码:

Function AvgNoColor(rngData As Range, color As String) As Variant Dim sum As Double Dim amount As Double Dim C As Range For Each C In rngData If color = "Red" Then If Not COLORINDEX(C) = 44 And Not COLORINDEX(C) = 3 Then sum = sum + C.Value amount = amount + 1 Else 'HERE AvgNoColor = "" End If ElseIf color = "Orange" Then If Not COLORINDEX(C) = 44 Then sum = sum + C.Value amount = amount + 1 Else 'HERE AvgNoColor = "" End If End If Next AvgNoColor = sum / amount End Function 

简而言之,我想要一个范围内的单元格的平均值不是颜色“红色”或“橙色”。 平均值按预期返回,但是当单元格需要为空时,单元格会收到#VALUE错误。

通过将这一行( AvgNoColor = sum / amount )放在if-else块之外,您已经将代码打开为零/未定义,如果被触发,将在每个方向上引发错误。

试试这个修订:

 Function AvgNoColor(rngData As Range, color As String) As Variant Dim sum As Double Dim amount As Double Dim C As Range For Each C In rngData If color = "Red" Then If Not COLORINDEX(C) = 44 And Not COLORINDEX(C) = 3 Then sum = sum + C.Value amount = amount + 1 End If ElseIf color = "Orange" Then If Not COLORINDEX(C) = 44 Then sum = sum + C.Value amount = amount + 1 End If End If Next If sum <> 0 And amount <> 0 Then AvgNoColor = sum / amount Else AvgNoColor = "" End If End Function 

尝试ISERROR(值)function:

 If Not IsError(AvgNoColor) Then 'your code End If 

如果值是一个错误值(#N / A,#VALUE !, #REF !,#DIV / 0!,#NUM!,#NAME?或#NULL),则此函数将返回TRUE。 否则,它将返回FALSE。

请尝试细胞

 =IF(ISERROR(AvgNoColor(A3:A14,"Red"))="FALSE",AvgNoColor(A3:A14,"Red"),"")