2015-09-30 32 views
1

我在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 

回答

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 

(檢查只是爲空值是更具體的從數據庫中導入數據)

+1

謝謝。但是value2的用途是什麼? –

+0

使用單元格(範圍)時,有3個屬性用於從Range對象獲取實際數據:「rng.Value」,「rng.Value2」和「rng.Text」。例如,如果A1包含NOW():.Text:** ####### **(當列太窄而不能顯示整個值時)'rng.Value2'是「原始數據」 ,.Value:** 9/28/2015 6:43:43 PM **,.Value2:** 42275.7803555556 **。 [這個答案](http://stackoverflow.com/questions/17359835/what-is-the-difference-between-text-value-and-value2)有關於他們之間的差異更多的信息 –

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 
+0

你可能想擴大你的回答解釋附加功能的作用。 – Gareth