2012-08-24 41 views
1

我有以下代碼:InStr函數沒有找到子

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的」,我得到的案例否則調用(正確的調用)
  2. 對於「」,我得到的發現消息(應該是空的消息)
  3. 對於「Renolds,鮑勃」 ,我得到Case Else電話(應該得到找到的信息)

這是怎麼回事?

回答

4

您使用Select Case語法的方式似乎是問題所在。你的每個案例都包含一個計算。因此,在進行「Select Case」比較之前,VB會對每個案例進行計算。

例如:對於您的第一個循環,單元=「Renolds,Bob」。因此,您的第一個Case條件將評估InStr(1,cell,「,」)爲8,它將評估(8 <> 0)爲True。然而,「Renolds,Bob」不等於(InStr(1,cell,「,」)<> 0)',其等於真。奇怪的是,當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

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