vba 使用VBA检查下面的单元格是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10263644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:01:13  来源:igfitidea点击:

Using VBA to check if below cell is empty

excelexcel-vbavba

提问by cherrun

How do I use VBA in Excel to check if a below cell is empty or not? I want to sum all values in a specific range, but only, if the below cell is not empty.

如何在 Excel 中使用 VBA 检查下面的单元格是否为空?我想对特定范围内的所有值求和,但前提是下面的单元格不为空。

Is that somehow possible with VBA or any other way?

用 VBA 或任何其他方式可以实现吗?

Example:

例子:

4 2 3 2 1
2   3 1

Sum would be: 4 + 3 + 2 = 9.

总和为:4 + 3 + 2 = 9。

采纳答案by Siddharth Rout

I would recommend a Formula for this

我会为此推荐一个公式

FORMULA

公式

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

SNAPSHOT

快照

enter image description here

在此处输入图片说明

If you still want VBA then

如果你仍然想要 VBA 那么

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

In fact you can have many versions in VBA. You can evaluate the above formula as well. For example

事实上,您可以在 VBA 中有许多版本。您也可以评估上述公式。例如

Option Explicit

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

回答by Nick

Try this simple code

试试这个简单的代码

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

回答by LeasMaps

I've had some problems using just 'IsEmpty' when the data is exported from other databases. This is the function I've developed:

当数据从其他数据库导出时,我在使用“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