InStr没有找到子串

时间:2012-08-24 17:12:13

标签: string excel vba contains select-case

我有以下代码:

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列中:F我按顺序排列如下:"Marc Jacobs", "", "Renolds, Bob" InStr没有找到任何正确的案例陈述。

  1. 对于&#34; Marc Jacobs&#34;,我接到Case Else电话(正确的电话)
  2. 对于&#34;&#34;,我收到了找到的消息(应该是空消息)
  3. 对于&#34; Renolds,Bob&#34;,我接到Case Else电话(应该收到找到的消息)
  4. 这是怎么回事?

2 个答案:

答案 0 :(得分:4)

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

例如:对于你的第一个循环,cell =“Renolds,Bob”。因此,您的第一个Case条件将InStr(1,cell,“,”)评估为8,它将评估(8&lt;&gt; 0)为True。然而,“Renolds,Bob”不等于(InStr(1,cell,“,”)&lt;&gt; 0)'等于True。奇怪的是,当VBA将“”转换为布尔值时,它可以比较它们,“”转换为True。

你可能想写的是

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

答案 1 :(得分:1)

您也可以使用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