Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 445
user2569803 Avatar asked Jul 11 '13 13:07

user2569803


People also ask

How do you break an if statement in VBA?

In VBA, when you use the IF statement, you can use a GoTo statement to Exit the IF. Let me clear here; there's no separate exit statement that you can use with IF to exit. So, it would be best if you used goto to jump out of the IF before the line of the end statement reach.

Does != Work in VBA?

Bookmark this question. Show activity on this post. The problem is that != does not work as a function in excel vba.

How do you use multiple conditions in if statement Excel VBA?

You can use the AND operator with the VBA IF statement to test multiple conditions, and when you use it allows you to test two conditions simultaneously and get true if both of those conditions are true. And, if any of the conditions is false it returns false in the result.

How do I use InStr in Excel VBA?

The syntax of VBA InStr is “InStr([start],string1,string2,[compare]).” In comparison, the syntax of InStrRev is “InStrRev(string1,string2,[start,[compare]]).” If the “start” argument is omitted, the InStr begins to search from the starting (first position) of the string.


1 Answers

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
like image 122
Alex K. Avatar answered Sep 28 '22 07:09

Alex K.