VBA 应用程序中有一个If
条件,如下所示:
If Not My_Object Is Nothing Then
My_Object.Compute
当代码在调试模式下运行时,我发现If
即使My_Object
有“无变量”,条件也会返回 true。
有人可以解释一下吗?我只想My_Object.Compute
在My_Object
存在时被执行。
VBA 应用程序中有一个If
条件,如下所示:
If Not My_Object Is Nothing Then
My_Object.Compute
当代码在调试模式下运行时,我发现If
即使My_Object
有“无变量”,条件也会返回 true。
有人可以解释一下吗?我只想My_Object.Compute
在My_Object
存在时被执行。
根据您对 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
还值得注意的是,如果您声明任何对象As New
,则Is Nothing
检查将变得无用。原因是当您声明一个对象As New
时,它会在第一次调用时自动创建,即使您第一次调用它是为了查看它是否存在!
Dim MyObject As New Collection
If MyObject Is Nothing Then ' <--- This check always returns False
这似乎不是您的特定问题的原因。但是,由于其他人可能会通过谷歌搜索找到这个问题,所以我想把它包括在内,因为这是一个常见的初学者错误。
仅仅因为你的类对象没有变量并不意味着它什么都不是。声明对象和创建对象是两件不同的事情。查看您是否正在设置/创建对象。
以字典对象为例——仅仅因为它不包含变量并不意味着它没有被创建。
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
但是,如果您声明一个对象但从未创建它,那什么都不是。
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
在我的示例代码中,我没有设置my object
任何内容,并且我无法让 if 语句的“not”部分与对象一起使用。if My_Object is not nothing
我也试过了if not My_Object is nothing
。这可能只是我无法弄清楚的语法问题,但我没有时间搞砸,所以我做了一个像这样的小解决方法:
if My_Object is Nothing Then
'do nothing
Else
'Do something
End if