VBA:有条件 - 没什么

Sta*_*tar 21 vba if-statement excel-2007 excel-vba nothing

IfVBA应用程序中有一个条件如下所示:

If Not My_Object Is Nothing Then
My_Object.Compute
Run Code Online (Sandbox Code Playgroud)

当代码在调试模式下运行时,我发现If即使My_Object具有"无变量" ,条件也会返回true .

有人可以解释一下吗?我想My_Object.Compute只在My_Object存在时执行.

mwo*_*e02 24

根据您对Issun的评论:

感谢您的解释.在我的例子中,对象是在If条件之前声明和创建的.那么,我如何使用If条件来检查<No Variables>?换句话说,如果My_Object具有<No Variables>,我不想执行My_Object.Compute

您需要检查对象的一个​​属性.在不告诉我们对象是什么的情况下,我们无法帮助您.

我测试了几个常见对象,发现在监视窗口中Collection显示没有添加任何项目的实例化<No Variables>.如果您的对象确实是一个集合,您可以<No Variables>使用该.Count属性检查条件:

Sub TestObj()
Dim Obj As Object
    Set Obj = New Collection
    If Obj Is Nothing Then
        Debug.Print "Object not instantiated"
    Else
        If Obj.Count = 0 Then
            Debug.Print "<No Variables> (ie, no items added to the collection)"
        Else
            Debug.Print "Object instantiated and at least one item added"
        End If
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

值得注意的是,如果您声明任何对象,As NewIs Nothing检查变得无用.原因是当你声明一个对象As New时,它会在第一次被调用时自动创建,即使你第一次调用它是为了查看它是否存在!

Dim MyObject As New Collection
If MyObject Is Nothing Then  ' <--- This check always returns False
Run Code Online (Sandbox Code Playgroud)

这似乎不是您特定问题的原因.但是,由于其他人可能会通过谷歌搜索找到这个问题,我想把它包括在内,因为这是一个常见的初学者错误.


aev*_*nko 10

只是因为你的类对象没有变量并不意味着它什么都没有.声明和对象以及创建对象是两回事.查看并查看是否正在设置/创建对象.

以字典对象为例 - 仅仅因为它不包含变量并不意味着它没有被创建.

Sub test()

Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

If Not dict Is Nothing Then
    MsgBox "Dict is something!"  '<--- This shows
Else
    MsgBox "Dict is nothing!"
End If

End Sub
Run Code Online (Sandbox Code Playgroud)

但是,如果您声明一个对象但从未创建它,那就没什么了.

Sub test()

Dim temp As Object

If Not temp Is Nothing Then
    MsgBox "Temp is something!"
Else
    MsgBox "Temp is nothing!" '<---- This shows
End If

End Sub
Run Code Online (Sandbox Code Playgroud)

  • 没有看到你的代码和对象是什么,我恐怕我不知道如何帮助你. (4认同)