Search code examples
vbaif-statementshort-circuiting

VBA: Error thrown when using Or (In an If-Then statement), the first condition tests if object is nothing


For a custom object, I want to test two conditions. The first is whether the object is nothing. If so, enter the block. If the object is not nothing, I want to do a test on one of the object's properties, and only enter the block if it passes this test.

So the statement would by akin to:

If myObject Is Nothing Or myObject.myInt > x Then
    'Perform my task
End If

If myObject is in fact nothing, this throws an error, since when it tests the second condition, it tries to access a property of an object that isn't there.

Most languages I've worked with in the past would not bother to test the second condition of an Or statement if it found the first condition to be true, so you could get away with writing the line above. VBA doesn't seem to allow this. Is there any equivalent way i could write this statement, without resorting to:

If myObject Is Nothing Then
    'Perform my task
ElseIf myObject.myInt > x Then
    'Perform my task
End If

?

EDITED FOR CLARITY


Solution

  • You could create a flag:

    PerformTheTask = False
    
    If myObject Is Nothing Then
        PerformTheTask = True
    ElseIf myObject.myInt > x Then
        PerformTheTask = True
    End If
    
    If PerformTheTask Then
        'Perform my task
    End If