VBA checks if an object is installed

I have a global variable that is an instance of my custom class.

How to check if an object is installed or if it needs to be initialized?

+46
vba ms-access
Apr 13 '10 at 17:20
source share
2 answers
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 
+78
Apr 13 '10 at 17:22
source share
— -

(un) a safe way to do this - if you're okay without using the option explicitly - this is ...

 Not TypeName(myObj) = "Empty" 

It also handles the case if the object was not declared. This is useful if you just want to comment on an ad to disable some behavior ...

 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 automatically create an undeclared variable as the type of Empty Variant. This eliminates the need for auxiliary logic to control behavior.

0
Oct 30 '16 at 3:10
source share



All Articles