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 was 0. Similarly, you can use 0 in a logical expression as though it was False. -
A True result can be used in an expression as though it was “1. However, any nonzero value can be used in a logical expression as though it was True. In Chapter 6, "Controlling Your VBA Code," I'll show you various VBA statements that let your procedures make decisions and loop through sections of code. 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 of 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 if they're both True. For example, consider the following generic expression (where Expr1 and Expr2 are Boolean values): Expr1 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 if 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 if 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. |