Reputation: 43
I would like to know how to have Select Case continue running after it encounters first expression that evaluates to true. In the below example, only message box "Z is less than 9" will be triggered. I would like to know how to have code continue so that, in this example, message box "Z is less than 10" will be shown after "Z is less than 9"
Sub SelectCaseTrying()
Dim Z As Integer
Z = 8
Select Case Z
Case 5 To 9
MsgBox "Z is less than 9"
Case Is < 10
MsgBox "Z is less than 10"
Case Is > 15
MsgBox "Z is greater than 15"
Case Else
MsgBox "Z is "
End Select
End Sub
Upvotes: 2
Views: 3103
Reputation: 71167
I would like to know how to have Select Case continue running after it encounters first expression that evaluates to true.
You can't have that, because as per language specifications, Case
blocks don't "fall through" in VBA, so if you had this:
Select Case Z
Case Is < 15
MsgBox "less than 15"
Case Is < 10
MsgBox "less than 10"
Case Else
MsgBox "greater than or equal to 10"
End Select
Then the second Case
is heuristically unreachable - and a static code analysis tool like Rubberduck (disclaimer: I'm a contributor to this open-source project), can warn about that:
Think of Select...Case
as a cleaner way to write If...ElseIf...ElseIf...ElseIf...ElseIf...
blocks: the conditions should all be mutually exclusive, and only one branch gets to execute.
If you need two or more conditional blocks to run, then you can't use a Select...Case
because that's not what If...ElseIf...ElseIf...
does: if you need two or more conditional blocks to run, you need two or more separate conditional blocks (If...End If
).
Upvotes: 2