Working with Logical Expressions
A logical expression is an expression that returns a Boolean result. A Boolean value is almost always either True or False, but VBA also recognizes some Boolean equivalents:
- A False result can be used in an expression as though it were 0. Similarly, you can use 0 in a logical expression as though it were False.
- A True result can be used in an expression as though it were -1. However, any nonzero value can be used in a logical expression as though it were True.
In most cases, the mechanism that controls these statements will be a logical expression. For example, if x is a logical expression, you can tell VBA to run one set of statements if x returns True and a different set of statements if x returns False.
You'll see that these are powerful constructs, and they'll prove invaluable in all your VBA projects. To help you prepare, let's take a closer look at VBA's logical operators.
The And Operator
You use the And operator when you want to test two Boolean operands to see whether they're both true. For example, consider the following generic expression (where Expr1 and Expr2 are Boolean values):
xpr1 And Expr2
- If both Expr1 and Expr2 are true, this expression returns True.
- If either or both Expr1 and Expr2 are false, the expression returns False.
The Or Operator
You use the Or operator when you want to test two Boolean operands to see whether one of them is true:
Expr1 Or Expr2
- If either or both Expr1 and Expr2 are true, this expression returns True.
- If both Expr1 and Expr2 are false, the expression returns False.
The Xor Operator
Xor is the exclusive Or operator. It's useful when you need to know whether two operands have the opposite value:
Expr1 Xor Expr2
- If one of the values is true and the other is false, the expression returns True.
- If Expr1 and Expr2 are both true or are both false, the expression returns False.
The Not Operator
The Not operator is the logical equivalent of the negation operator. In this case, Not returns the opposite value of an operand. For example, if Expr is true, Not Expr returns False.