VBA用户定义的范围,并检查其是否为空

时间:2019-07-26 18:36:44

标签: excel 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)不能正常工作。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:2)

您的问题是您的变量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

答案 1 :(得分:0)

只需一些代码

services.AddMvc()
        .AddJsonOptions(options =>
         {
             options.SerializerSettings.ContractResolver
                 = new Newtonsoft.Json.Serialization.DefaultContractResolver();
         });

答案 2 :(得分:0)

如果仅对存在的数据实例进行操作,则类似下面的内容将起作用。我还将在代码顶部添加Option Explicit并声明所有变量。

Sub How()

Dim rng As Range
Set rng = Application.InputBox("Select Target Range", Type:=8)

If Application.WorksheetFunction.CountA(rng) <> 0 Then
    'Actions
End If

End Sub