There is an If
condition in a VBA application as seen below:
If Not My_Object Is Nothing Then
My_Object.Compute
When the code is run in debug mode, I found that the If
condition returns a true even when My_Object
has "No Variables".
Could somebody please explain this? I want My_Object.Compute
to be executed only when My_Object
exists.
Based on your comment to Issun:
You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.
I did test several common objects and found that an instantiated
Collection
with no items added shows<No Variables>
in the watch window. If your object is indeed a collection, you can check for the<No Variables>
condition using the.Count
property:It is also worth noting that if you declare any object
As New
then theIs Nothing
check becomes useless. The reason is that when you declare an objectAs New
then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
However if you declare an object but never create it, it's nothing.
In my sample code, I was setting
my object
to nothing, and I couldn't get the "not" part of the if statement to work with the object. I triedif My_Object is not nothing
and alsoif not My_Object is nothing
. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this: