InStr not finding substring
-
28-06-2021 - |
Вопрос
I have the following code:
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
In column F:F I have the following in order: "Marc Jacobs", "", "Renolds, Bob"
InStr is not finding any of the proper case statements.
- For "Marc Jacobs", I get the Case Else call (Correct call)
- For "", I get the found message (Should be the empty message)
- For "Renolds, Bob", I get the Case Else call (Should get the found message)
Whats going on here?
Решение
The way that you are using the Select Case syntax seems to be the problem. Each of your Cases contains a calculation. So, VB will do the calculation for each of the Cases before it does the "Select Case" comparisons.
For example: for your first loop, the cell="Renolds, Bob". So your first Case condition will evaluate InStr(1,cell,",") as 8 and it will evaluate (8<>0) to True. However, "Renolds, Bob" does not equal (InStr(1,cell,",") <> 0) 'which equals True. Oddly, when VBA converts "" to a boolean, so it can compare them, "" converts to True.
What you probably wanted to write was
For Each cell in Selection
If InStr(1, cell, ",") <> 0 Then
MsgBox("found")
ElseIf IsEmpty(cell)
MsgBox("empty")
Else
Stop
End If
Next
Другие советы
You can use Select...Case statement too:
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