2012-04-21 100 views
7

如何在Excel中使用VBA來檢查下面的單元格是否爲空? 我想總結一個特定範圍內的所有值,但只有在下面的單元格不爲空的情況下。使用VBA檢查下面的單元格是否爲空

這是用VBA或其他方式以某種方式可能嗎?

實施例:

4 2 3 2 1 
2 3 1 

薩姆將是:4 + 3 + 2 = 9。

回答

4

我建議一個公式此

FORMULA

=SUMPRODUCT((A1:E1)*(A2:E2<>"")) 

SNAPSHOT

enter image description here

如果你仍然想VBA然後

VBA

Option Explicit 

Sub Sample() 
    Dim rng As Range 
    Dim Cl As Range 
    Dim tot As Long 

    Set rng = Range("A1:F1") 

    For Each Cl In rng 
     If Len(Trim(Cl.Offset(1))) <> 0 Then tot = tot + Cl.Value 
    Next 

    Debug.Print tot 
End Sub 

事實上,你可以在VBA很多版本。您也可以評估上述公式。例如

Option Explicit 

Sub Sample() 
    Debug.Print Evaluate("=SUMPRODUCT((A1:E1)*(A2:E2<>""""))") 
End Sub 
+0

@Siddarth Rout,非常好的方法。 – Marc 2012-04-21 23:06:50

+0

不錯!你介意在這部分詳細說明:'<>「」'? – cherrun 2012-04-22 00:30:17

+1

@Cherrun:「<>」代表「不等於」。所以我只考慮在A2:E2範圍內不爲空的單元格。 – 2012-04-22 08:13:52

9

試試這個簡單的代碼

If IsEmpty(ActiveCell.Offset(1, 0)) Then 
'your code here 
End If 
1

我當數據從其他數據庫導出只使用「爲IsEmpty」出現了一些問題。這是我開發的功能:

Function IsVacant(TheVar As Variant) As Boolean 
    'LeandraG 2010 

    IsVacant = False 

    If IsEmpty(TheVar) Then IsVacant = True 
    If Trim(TheVar) = "" Then IsVacant = True 
    If Trim(TheVar) = "'" Then IsVacant = True 


End Function 
相關問題