O'Reilly logo

Programming Excel with VBA and .NET by Steve Saunders, Jeff Webb

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required