Logical and Bitwise Operators
Logical operators allow you to
evaluate one or more expressions and return a logical value. VBA
supports six logical operators: And,
Or, Not,
Eqv, Imp, and
Xor. These operators also double as bitwise
operators. A bitwise comparison examines each bit position in both
expressions and sets or clears the corresponding bit in the result
depending upon the operator used. The result of a bitwise operation
is a numeric value. Typically, bitwise operations are used rarely in
a scripted language, though the capability is available in VBScript
if you need it.
-
And Performs logical conjunction; that is, it returns
Trueonly if bothexpression1andexpression2evaluate toTrue. If either expression isFalse, then the result isFalse. If either expression isNull, then the result isNull. Its syntax is:result = expression1 And expression2
For example:
If x = 5 And y < 7 Then
In this case, the code after the
Ifstatement will be executed only if the value ofxis five and the value ofyis less than seven.As a bitwise operator, And returns 1 if the compared bits in both expressions are 1, and returns in all other cases, as shown in the following table:
|
Bit in expression1 |
Bit in expression2 |
Result |
|---|---|---|
|
0 |
0 |
0 |
|
0 |
1 |
0 |
|
1 |
0 |
0 |
|
1 |
1 |
1 |
For example, the result of 15 And 179 is 3, as the
following binary representation shows:
00000011 = 00001111 And 10110011
-
Or Performs logical disjunction; that is, if either
expression1orexpression2evaluates toTrue, or if both ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access