VBA: Conditional - Is Nothing

后端 未结 3 2086
半阙折子戏
半阙折子戏 2020-12-16 11:34

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

3条回答
  •  执念已碎
    2020-12-16 12:15

    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 in the watch window. If your object is indeed a collection, you can check for the 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 " (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.

提交回复
热议问题