Find Truth

If statements and Do loops rely on Boolean expressions to control what they do. Those Boolean expressions are usually shown as a condition placeholder in the statement’s syntax:

    If condition Then ...

and:

    Do While condition ...

A Boolean expression is simply an item that Visual Basic can determine to be either True or False. Mostly those expressions are very obvious. The fragment If str = "" Then says “if the variable str is an empty string, then execute the following lines of code.” In this case, the equal sign (=) works as a comparison operator, not an assignment operator. Visual Basic can use the operator both ways because it understands that the context of an If statement is different from the standalone statement:

    str = ""

That line performs an assignment, not a comparison! This type of dual use is called overloading . If you hear someone say “operators are overloaded in Visual Basic,” they are just stating that = can be used two different ways.

There’s something else you need to know about Boolean expressions, though. In Visual Basic, any nonzero value is considered to be True. I know that’s weird, but it’s important because it means the following two fragments are equivalent:

    If str = "" Then ...

    If Len(str) Then ...

The second form literally says “if the length of str, then...” which doesn’t make any sense unless you know that 0 equals False and any other value equals True. This second form used to be a common optimization technique because Visual Basic ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.