如何在excel中检测空值?

时间:2015-09-30 02:19:25

标签: excel-vba vba excel

我在excel中遇到了值检测问题。如果它没有在单元格中有价值我想要excel显示消息警告而不是零值,我有下面的代码。

Public Function MySum(a As Range, b As Range) As String

    If IsNull(a) And IsNull(b) Then
        MySum = "No value sir"
    Else
        MySum = a.Value + b.Value
    End If

End Function

2 个答案:

答案 0 :(得分:0)

以下是验证参数的几种方法

Option Explicit

Public Function MySum(a As Range, b As Range) As String
    Dim itmsOK As Boolean

    MySum = "No value"  'default return value, if a or b are not valid

    itmsOK = (Not a Is Nothing And Not b Is Nothing)    'validate the Range objects

    If itmsOK Then itmsOK = (Not IsNull(a.Value2) And Not IsNull(b.Value2))       'DB vals
    If itmsOK Then itmsOK = (Len(Trim(a.Value2)) > 0 And Len(Trim(b.Value2)) > 0) 'Empty
    If itmsOK Then itmsOK = (IsNumeric(a.Value2) And IsNumeric(b.Value2))         'Numbers

    If itmsOK Then MySum = Val(a.Value2) + Val(b.Value2)   'if both valid, perform math

End Function

(仅检查Null对于从数据库导入数据更具体)

答案 1 :(得分:0)

CountA函数返回值" 0"当细胞是空的时候。因此,在这种情况下,您可以使用CountA函数来检查单元格中是否有任何数据。

If CountA("a") = 0 and CountA("b") = 0 Then
MySum = "No value sir"
    Else
MySum = a.Value + b.Value
Else IF
END