2012-04-21 103 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 
相关问题