It's not uncommon to include two or more comparisons in a conditional statement like this:
If X < 0 And Y > 100 Then
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
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!