如果范围中的所有单元格都是数字,则对范围求和,否则返回错误

时间:2014-05-22 17:44:34

标签: vba excel-vba excel

注意:我正在将一系列单元格传递给该函数。范围中的每个单元格都包含一个返回数字或字符串的公式。以下代码始终返回错误。我认为代码返回错误,因为它正在查看单元格中的公式而不是公式的结果。我希望代码在每个单元格中测试结果(数字或字符串),而不是测试产生结果的公式。我认为.value属性会处理这个问题,但显然不会。

Function SmartSum(sumRange As Range) As Variant
'returns the sum of the the passed range IFF all elements in the range are numeric
'returns error if any of the elements in the range are not numeric, e.g., a text string

Dim ary As Variant
Dim i   As Long

ary = sumRange
SmartSum = 0

'sum all cells in range if they are numeric
'return an error if they are not
For i = LBound(ary, 1) To UBound(ary, 1)
    If IsNumeric(ary(i, 1)) Or ary(i, 1) = "" Then
        SmartSum = SmartSum + ary(i, 1)
    Else
        SmartSum = CVErr(xlErrValue)
    End If
Next

End Function

1 个答案:

答案 0 :(得分:2)

空字符串不是数字,因此当您尝试使用+运算符添加SmartSum时,会出现类型不匹配错误。 UDF中的所有错误均报告为#VALUE!错误,因此您无法判断您是否按设计返回错误,或者是否实际发生了错误。

此外,您还试图返回xlErrValue,但这并不是真正发生的事情。当您的代码遇到非数字时,它会将SmartSum更改为错误值。然后它尝试将下一个值添加到错误值,这会导致错误并且函数返回#VALUE!(因为内部错误,而不是因为CVError()函数)。

如果您将xlErrValue更改为xlErrNA,您的功能仍会返回#VALUE!。如果你想返回一个不同的错误,你可以像这样重写你的函数。

Function SmartSum(sumRange As Range) As Variant
'returns the sum of the the passed range IFF all elements in the range are numeric
'returns error if any of the elements in the range are not numeric, e.g., a text string

Dim ary As Variant
Dim i   As Long
Dim vReturn As Variant

ary = sumRange
vReturn = 0

'sum all cells in range if they are numeric
'return an error if they are not
For i = LBound(ary, 1) To UBound(ary, 1)
    If IsNumeric(ary(i, 1)) Or Len(ary(i, 1)) = 0 Then
        vReturn = vReturn + ary(i, 1)
    Else
        vReturn = CVErr(xlErrNA)
        Exit For
    End If
Next i

SmartSum = vReturn

End Function

当然,你不想这样做,它只是说明了发生了什么。使用上面的函数,空字符串将导致#VALUE!错误(函数中错误),但非数字将导致#N/A!错误(错误返回功能)。

要考虑空字符串,可以使用Val()函数强制值为数字。您已经检查了IsNumeric(),因此您唯一能做的就是强迫"是空字符串 - 其他所有内容都会愉快地转换为数字。

Function SmartSum(sumRange As Range) As Variant
'returns the sum of the the passed range IFF all elements in the range are numeric
'returns error if any of the elements in the range are not numeric, e.g., a text string

Dim ary As Variant
Dim i   As Long
Dim vReturn As Variant

ary = sumRange
vReturn = 0

'sum all cells in range if they are numeric
'return an error if they are not
For i = LBound(ary, 1) To UBound(ary, 1)
    If IsNumeric(ary(i, 1)) Or Len(ary(i, 1)) = 0 Then
        vReturn = vReturn + Val(ary(i, 1))
    Else
        vReturn = CVErr(xlErrValue)
        Exit For
    End If
Next i

SmartSum = vReturn

End Function