Search code examples
vbaboolean-operations

Boolean logic in VBA


I see unexpected behavior when using two AND operators and numbers: The third entry seems to be considered modulo 2. See the example below.

I would love to find out why the behavoir is like it is.

Sub Test()

Dim a As Boolean
Dim b As Boolean

a = True And 1 And 2 ' a = false
b = True And 2 And 3 ' b = true

MsgBox (a)
MsgBox (b)

End Sub

Solution

  • And is applied bitwise here

        1111  'true
    And 0001  '1
    And 0010  '2
    -------------
        0000  '0 -> evaluates to false when cast as boolean
    
        1111 'true
    And 0010 '2
    And 0011 '3
    -------------
        0010 '2 -> evaluates to true when cast as boolean