VBA 检查是否设置了对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2631678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA check if object is set
提问by Icode4food
I have a global variable that is an instance of my custom class.
我有一个全局变量,它是我的自定义类的一个实例。
How do I check if the object is set or if I need to initialize it?
如何检查对象是否已设置或是否需要初始化?
回答by stakx - no longer contributing
If obj Is Nothing Then
' need to initialize obj: '
Set obj = ...
Else
' obj already set / initialized. '
End If
Or, if you prefer it the other way around:
或者,如果您喜欢相反的方式:
If Not obj Is Nothing Then
' obj already set / initialized. '
Else
' need to initialize obj: '
Set obj = ...
End If
回答by Cool Blue
The (un)safe way to do this - if you are ok with not using option explicit - is...
执行此操作的(不)安全方法 - 如果您可以不使用选项显式 - 是...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
如果对象尚未声明,这也会处理这种情况。如果您只想注释掉声明以关闭某些行为,这很有用...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
这是有效的,因为 VBA 会将未声明的变量自动实例化为 Empty Variant 类型。它消除了对辅助布尔值来管理行为的需要。

