user2569803
user2569803

Reputation: 637

Excel VBA instr if statement false

I'm trying to not look for value 2, however "shouldn't happen" gets shown rather then the else, "ok".

If Not InStr("1, 2, 3", "2") Then
    MsgBox ("shouldn't happen")
Else
    MsgBox ("ok")
End If

We know the value is within the string. yet for some reason the "not" is not working. Does anyone know why?

Upvotes: 5

Views: 18856

Answers (1)

Alex K.
Alex K.

Reputation: 175766

Thats because

?InStr("1, 2, 3", "2")
 4 

and

?not 4
-5 // bitwise not of 4

which is a truthy value (cbool(-5) = true), so instead you need to:

if InStr("1, 2, 3", "2") = 0 then
  // not found
else 
  // found

Upvotes: 7

Related Questions