excelvbaif-statementexcel-2007

VBA: Conditional - Is Nothing


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.


Solution

  • Based on your comment to Issun:

    Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>

    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:

    Sub TestObj()
    Dim Obj As Object
        Set Obj = New Collection
        If Obj Is Nothing Then
            Debug.Print "Object not instantiated"
        Else
            If Obj.Count = 0 Then
                Debug.Print "<No Variables> (ie, no items added to the collection)"
            Else
                Debug.Print "Object instantiated and at least one item added"
            End If
        End If
    End Sub
    

    It is also worth noting that if you declare any object As New then the Is Nothing check becomes useless. The reason is that when you declare an object As 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!

    Dim MyObject As New Collection
    If MyObject Is Nothing Then  ' <--- This check always returns False
    

    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.