Search code examples
vbaoperatorsbitwise-operatorsbitwise-not

(Not 1) evaluates to -2 for some reason


Why does (Not 1) evaluate as -2? I would expect it to evaluate as 0.

enter image description here


Solution

  • VBA/VBScript does not have real logical operators (AND, OR, NOT). The logical operators you see are actually bitwise operators, and that's all you get. VBA plays some games with the True and False values so this works most of the time, but occasionally you'll find a "gotcha".

    In this case, instead of If Not InStr() Then you have to write If InStr() <= 0 Then.
    Instead of If InStr() Then you have to write If InStr() > 0 Then

    In other words: InStr() returns a number. Don't try to treat it like a boolean.