Excel VBA instr if语句为false

use*_*803 4 string excel vba if-statement contains

我试图寻找值2,但是"不应该发生"会显示而不是其他,"确定".

If Not InStr("1, 2, 3", "2") Then
    MsgBox ("shouldn't happen")
Else
    MsgBox ("ok")
End If
Run Code Online (Sandbox Code Playgroud)

我们知道值在字符串中.但由于某种原因,"不"不起作用.有谁知道为什么?

Ale*_* K. 6

那是因为

?InStr("1, 2, 3", "2")
 4 
Run Code Online (Sandbox Code Playgroud)

?not 4
-5 // bitwise not of 4
Run Code Online (Sandbox Code Playgroud)

这是一个值(cbool(-5) = true),所以你需要:

if InStr("1, 2, 3", "2") = 0 then
  // not found
else 
  // found
Run Code Online (Sandbox Code Playgroud)