InStr没有find子string

我有以下代码:

Columns("F:F").Select For Each cell In Selection Select Case cell Case InStr(1, cell, ",") <> 0 MsgBox ("found") Case IsEmpty(cell) Or Null MsgBox ("empty") Case Else Stop End Select Next 

在F列中:FI具有以下顺序: "Marc Jacobs", "", "Renolds, Bob" InStr没有find任何适当的案例陈述。

  1. 对于“Marc Jacobs”,我得到了Case Else的电话(正确的电话)
  2. 对于“”,我得到的消息(应该是空的消息)
  3. 对于“Renolds,Bob”,我得到了Case Else调用(应该得到find的消息)

这里发生了什么?

您使用Select Case语法的方式似乎是问题所在。 你的每个案例都包含一个计算。 因此,VB会在进行“Select Case”比较之前对每个案例进行计算。

例如:对于你的第一个循环,单元格=“Renolds,Bob”。 所以你的第一个Case条件将评估InStr(1,cell,“,”)为8,它将评估(8 <> 0)为True。 但是,“Renolds,Bob”不等于(InStr(1,cell,“,”)<> 0)“,它等于True。 奇怪的是,当VBA将“”转换为布尔值时,可以将它们进行比较,“”转换为“真”。

你可能想要写的是

 For Each cell in Selection If InStr(1, cell, ",") <> 0 Then MsgBox("found") ElseIf IsEmpty(cell) MsgBox("empty") Else Stop End If Next 

您也可以使用Select … Case语句:

 For Each cell In Selection Select Case True Case InStr(1, cell, ",") <> 0 MsgBox ("found") Case IsEmpty(cell) MsgBox ("empty") Case Else Stop End Select Next