Compare Bits
Computers use binary numbers internally. That’s because they don’t have 10 fingers to count on; they have only 2: on and off, which represent 1 and 0, respectively. Knowing that helps you understand another use for the operators in Table 3-18—Boolean operators can also be used in mathematical operations to change the individual bits that make up a number, as illustrated by the following code:
Sub ToBorNotToB( ) Dim b As Byte b = 93 Debug.Print b, Not b, b Or Not b ' Displays: 93 162 255 End Sub
In the preceding code, Not
and Or
have a mathematical effect on b
. Specifically, Not
returns the bits that are 0 (255 - b) and Or
combines the bits in b
and Not b
(93 + 162). These are called bitwise operations and they make more sense if you look at b
as a binary number (Figure 3-3).
Bitwise operations are used to determine if a number contains one or more bit flags . Bit flags are numeric constants that can be combined in a single number without interfering with each other, as shown in Figure 3-4.
Figure 3-4 illustrates that the result of the VarType
function can contain both the vbArray
flag and any of the other type flags. For instance, vbArray And vbVariant
indicates an array of variants. You can test if a variable contains an array of variants by combining the type flags with the Or
operator:
Figure 3-3. Evaluating bitwise operations
Figure 3-4. VbVarType constants ...
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.