VBA check if object is set

前端 未结 2 1512
生来不讨喜
生来不讨喜 2020-12-25 09:08

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?

2条回答
  •  -上瘾入骨i
    2020-12-25 09:51

    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.

提交回复
热议问题