sta*_*ica 120
If obj Is Nothing Then
' need to initialize obj: '
Set obj = ...
Else
' obj already set / initialized. '
End If
Run Code Online (Sandbox Code Playgroud)
或者,如果你喜欢它,反过来说:
If Not obj Is Nothing Then
' obj already set / initialized. '
Else
' need to initialize obj: '
Set obj = ...
End If
Run Code Online (Sandbox Code Playgroud)
执行此操作的(不)安全方法 - 如果您可以不使用显式选项 - 是......
Not TypeName(myObj) = "Empty"
Run Code Online (Sandbox Code Playgroud)
如果对象尚未声明,这也可以处理这种情况。如果您只想注释掉声明以关闭某些行为,这非常有用......
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
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为 VBA 会将未声明的变量自动实例化为空变体类型。它消除了辅助布尔值来管理行为的需要。
小智 5
使用全局变量时,可能会遇到对象为空的情况。所以,代码:
If Not obj Is Nothing Then
'obj is already set
Else
'set obj
End If
Run Code Online (Sandbox Code Playgroud)
产生“需要对象”错误。
在这种情况下,可以进行以下操作:
'First check it is initialized
If IsObject(obj) Then
'Then check if it is set
If Not obj Is Nothing Then
'obj is set
Else
'set obj
End If
End If
Run Code Online (Sandbox Code Playgroud)