Excel Visual Basic - 检测范围是否为空

Kan*_*ano 29 excel vba range

我不知道是否可能,但我想检查Excel中的范围是否为空.那么我该怎么写:

If Range("A38":"P38") is empty
Run Code Online (Sandbox Code Playgroud)

在VBA代码中是空的吗?

提前致谢.

Kan*_*ano 51

从我得到的评论中找到了解决方案.

Sub TestIsEmpty()
    If WorksheetFunction.CountA(Range("A38:P38")) = 0 Then
        MsgBox "Empty"
    Else
        MsgBox "Not Empty"
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 注意:**"Empty()"**不是有效的程序名称.@ darren-bartrup-cook,我提议的编辑不会偏离帖子的原始意图并保留其目标. (3认同)
  • 如果该范围可能包含空字符串值(常量)或可能返回空字符串值的公式,并且具有空字符串值的单元格必须被视为“空”,则改用此表达式:WorksheetFunction.CountBlank (Range("A38:P38")) = Range("A38:P38").Cells.Count (也许可以使用 With 语句来清理它。) (2认同)

Mar*_*oy2 9

如果您发现自己处于无法使用的情况,CountA那么首先将范围存储为数组并在数组数据上循环比在范围/单元格数据上循环要快得多。

Function IsRangeEmpty(ByVal rng As Range) As Boolean
    'Converts a range to an array and returns true if a value is found in said array
    
    Dim area As Range
    For Each area In rng.Areas
        
        If area.Cells.Count > 1 Then
        
            'save range as array
            Dim arr As Variant
            arr = area.value
            
            'loop through array
            Dim cel As Variant
            For Each cel In arr
            
                'if cell is not empty then
                If Len(Trim(cel)) > 0 Then
                    IsRangeEmpty = False
                    Exit Function
                End If

            Next cel
            
        Else    'cannot loop on array with one value
            
            'if cell is not empty then
            If Len(Trim(area.Value2)) > 0 Then
                IsRangeEmpty = False
                Exit Function
            End If
            
        End If

    Next area

    IsRangeEmpty = True

End Function
Run Code Online (Sandbox Code Playgroud)

如何使用它的示例:

Sub Test()
    Debug.Print IsRangeEmpty(Range("A38:P38"))
End Sub
Run Code Online (Sandbox Code Playgroud)

如果Range("A38:P38")为空,则True在立即窗口中打印;否则它会打印False


Sha*_*kis 5

如果变量未初始化或显式设置为Empty,则IsEmpty返回True。否则,它返回False。如果expression包含多个变量,则始终返回False。IsEmpty仅返回有意义的变体信息。(https://msdn.microsoft.com/zh-cn/library/office/gg264227.aspx)。因此,您必须分别检查范围内的每个单元格:

    Dim thisColumn as Byte, thisRow as Byte

    For thisColumn = 1 To 5
        For ThisRow = 1 To 6
             If IsEmpty(Cells(thisRow, thisColumn)) = False Then
                 GoTo RangeIsNotEmpty
             End If
        Next thisRow
    Next thisColumn
    ...........
    RangeIsNotEmpty: 
Run Code Online (Sandbox Code Playgroud)

当然,这里的代码比使用CountA函数的解决方案的代码更多(不计数空单元格),但是,如果找到至少一个非空单元格,GoTo可以中断循环,并且可以更快地执行代码,尤其是当范围较大并且您需要检测这种情况时。同样,对于我来说,这段代码比不是VBA函数的Excel CountA函数更容易理解它的作用。