首页 > 解决方案 > VBA用户定义范围并检查它是否为空

问题描述

我已经为此苦苦挣扎了一个多小时。我需要编写一个 VBA 代码,让用户在其中选择一个范围,然后在我去做其他任何事情之前检查这个选定的范围是否为空。

这是我到目前为止所拥有的:

Sub test()
    Set rng= Application.InputBox("Select the range of the raw data please", Type:=8)
    If Application.WorksheetFunction.CountA(Range(rng)) > 0 Then
        MsgBox "do this, this and that!"
    End If
End Sub

当我运行它时,我得到一个“object_Global 的方法范围失败”。我知道它可以让用户很好地选择范围,但 Range(rng) 不能正常工作。任何帮助,将不胜感激!

标签: excelvba

解决方案


您的问题是您的变量rng是一个范围,而您试图将其包装在一个范围内,这就是它抛出错误的原因。试试这个。

Sub test()    
    Dim rng As Range
    Set rng = Application.InputBox("Select the range of the raw data please", Type:=8)

    If Application.WorksheetFunction.CountA(rng) > 0 Then
        MsgBox "do this, this and that!"
    End If

End Sub

推荐阅读