【问题标题】:#VALUE error when returning average or "" to cell with function将平均值或“”返回到具有函数的单元格时出现 #VALUE 错误
【发布时间】:2025-12-30 23:05:16
【问题描述】:

我有以下 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 错误。

【问题讨论】:

    标签: vba excel excel-formula


    【解决方案1】:

    通过将此行 (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
    

    【讨论】:

    • 它确实有效,但我不得不将变量 sum 和 amount 更改为变体,因为 double 不能是“”,所以它再次出错。现在可以正常工作了,谢谢!
    • 这是我的疏忽。我会纠正它。如果这对您有用,您应该通过单击答案旁边的复选标记来表明这一点。
    • 抱歉,我只是想通知您,以防您不知道。干杯和快乐的编码。
    【解决方案2】:

    试试 ISERROR(value) 函数:

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

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

    【讨论】:

    • 我尝试将IsError 放在For Each 之前和AvgNoColor = sum / amount 之后,并命令AvgNoColor = "",但这似乎不起作用。
    • 通过说“但是当一个单元格需要为空时,单元格会出现#VALUE 错误”,您的意思是为您的结果显示#VALUE,即平均值?
    • 我的意思是工作表中的单元格得到#VALUE而不是为空
    • 在显示 AvgNoColor 时写: Sub demo() If Not IsError(Cells(1, 4).Value) Then 'your code Cells(1, 1) = AvgNoColor 'replace Cells(1,1)使用您的单元格地址 Else Cells(1, 1) = "" '这将插入空字符串 End If End Sub
    【解决方案3】:

    请在单元格中尝试

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

    【讨论】:

    • 由于某种原因,现在我所有的单元格都是空的,除了应该是的单元格