Domanda

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.

  1. For "Marc Jacobs", I get the Case Else call (Correct call)
  2. For "", I get the found message (Should be the empty message)
  3. For "Renolds, Bob", I get the Case Else call (Should get the found message)

Whats going on here?

È stato utile?

Soluzione

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top