【问题标题】:Is there any way to shorten down this IsEmpty() and Range statement in VBA? [duplicate]有什么方法可以缩短 VBA 中的 IsEmpty() 和 Range 语句? [复制]
【发布时间】:2020-03-11 21:31:22
【问题描述】:

有没有办法用更好的范围声明来缩短这条线?当("C3:I3") 范围之外的一个单元格为空时,我需要它来生成一个 MsgBox,否则运行其余代码。

If IsEmpty(Range("C3")) = True Or IsEmpty(Range("D3")) = True Or IsEmpty(Range("E3")) = True Or IsEmpty(Range("F3")) = True Or IsEmpty(Range("G3")) = True Or IsEmpty(Range("H3")) = True Or IsEmpty(Range("I3")) = True Then

当我使用If IsEmpty(Range("C3:I3")) = True Then 时,代码的行为会有所不同,并且在只有一个单元格为空时不起作用。

【问题讨论】:

  • Detect if range is empty的可能重复
  • 对于accepted answer,将= 0 替换为= Range("C3:I3").Cells.Count。对于second answer,将= False 替换为= True
  • 是的,我确实已经找到了这个答案,但无法让它发挥作用。我会试试你的改动。
  • 您的评论对您有所帮助,我意识到WorksheetFunction.CountA(Range("C3:I3")) < 7 Then 在这种情况下会起作用

标签: excel vba


【解决方案1】:

试试这个:

Function IsRangeEmpty(ByRef theRange As Range) As Boolean
    Dim c As Range
    For Each c In theRange
        If Not IsEmpty(c) Then
            IsRangeEmpty = False
            Exit Function
        End If
    Next c
    IsRangeEmpty = True
End Function

【讨论】:

    【解决方案2】:

    您可以选择以下任何一种:

    循环范围

    Sub test()
    
        Dim rng As Range, cell As Range
    
        With ThisWorkbook.Worksheets("Sheet1")
    
            Set rng = .Range("C3:C13")
    
            For Each cell In rng
                If cell = "" Then
                    MsgBox "Empty cell!"
                End If
            Next
    
        End With
    
    End Sub
    

    将范围传递给数组和循环数组 - 更快:

    Sub test_1()
    
        Dim arr As Variant
        Dim i As Long
    
        With ThisWorkbook.Worksheets("Sheet1")
    
            arr = .Range("C3:C13")
    
            For i = LBound(arr) To UBound(arr)
                If arr(i, 1) = "" Then
                    MsgBox "Empty cell!"
                End If
            Next
    
        End With
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-25
      • 2015-03-17
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2023-02-06
      • 2019-12-23
      • 2014-01-28
      相关资源
      最近更新 更多