【问题标题】:InStr not finding substringInStr 找不到子字符串
【发布时间】:2012-08-20 06:43:37
【问题描述】:

我有以下代码:

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 没有找到任何正确的 case 语句。

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

这是怎么回事?

【问题讨论】:

    标签: string excel vba contains select-case


    【解决方案1】:

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

    例如:对于您的第一个循环,cell="Renolds, Bob"。因此,您的第一个 Case 条件会将 InStr(1,cell,",") 评估为 8,并将 (80) 评估为 True。但是,“Renolds, Bob”不等于 (InStr(1,cell,",") 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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-14
        • 2022-01-14
        • 1970-01-01
        • 2019-11-19
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多