Software Development optimize

Why you should be careful combining VB6 comparison operators

You may run into trouble when you include two or more VB6 comparisons in a conditional statement. Discover how you can avoid potential problems before they crop up.

It's not uncommon to include two or more comparisons in a conditional statement like this:

If X < 0 And Y > 100 Then
...
End If

However, there are times when this can get you into trouble, specifically when working with object references. For instance, perhaps you want to execute some code only if MyObj refers to a valid object and the object's Count property is > 0. You may try this:

If Not MyObj Is Nothing And MyObj.Count > 0

You might think that if MyObj is in fact Nothing that VB6 would not bother with the rest of the statement—specifically the MyObj.Count > 0 part. This is not the way VB works. If MyObj is Nothing, then VB will still try to evaluate MyObj.Count, which will cause an error. You can avoid this problem by nesting two If statements:

If Not MyObj Is Nothing Then
    If MyObj.Count > 0 Then
        ....
    End If
End If

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Peter Aitken's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

0 comments