开发者

VBA check if object is set

开发者 https://www.devze.com 2022-12-26 23:05 出处:网络
I have a global variable that 开发者_JS百科is an instance of my custom class. How do I check if the object is set or if I need to initialize it?If obj Is Nothing Then

I have a global variable that 开发者_JS百科is an instance of my custom class.

How do I check if the object is set or if I need to initialize it?


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


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.


When using global variables it's possible to run into a situation in which the object is empty. So, the code:

If Not obj Is Nothing Then
  'obj is already set
Else
  'set obj
End If

produces an 'object required' error.

In this situation, the following works:

'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
0

精彩评论

暂无评论...
验证码 换一张
取 消