Home » excel » How to fall through a Select Case in Excel VBA?

How to fall through a Select Case in Excel VBA?

Posted by: admin March 9, 2020 Leave a comment

Questions:

Given

Select Case cmd

    case "ONE":   MsgBox "one"

    case "TWO":   MsgBox "two"

    case "THREE": MsgBox "three"

End select

My requirement is if cmd = "ONE" I need "one" and then "two" displayed however currently I am getting "one" displayed and then the program is breaking out of the select case…

How to&Answers:
Select Case cmd
    case "ONE", "TWO":   
                  if cmd = "ONE" THEN
                      MsgBox "one"
                  end if
                  MsgBox "two"

    case "THREE": MsgBox "three"

End select

Answer:

Some if could do the job:

If cmd = "ONE" Then 
    MsgBox "one"
    cmd = "TWO"
End If
If cmd = "TWO" Then 
    MsgBox "two"
    cmd = "THREE"
End If
If Cmd = "THREE" Then 
    MsgBox "three"
End If

Answer:

You’ll just have to do it the long way.

Select Case cmd

    case "ONE":   MsgBox "one"
                  MsgBox "two"
                  MsgBox "three"

    case "TWO":   MsgBox "two"
                  MsgBox "three"

    case "THREE": MsgBox "three"

End select

Answer:

That is by design. http://msdn.microsoft.com/en-us/library/ee177199%28PROT.10%29.aspx

You could try using ‘goto’ or procedure calls to get around it.

Answer:

Why use Select Case for this? All you’re doing is printing the lower-case version of whatever value ‘cmd’ is.

If cmd = "ONE" Then
  MsgBox LCase$(cmd)
  MsgBox "two"
Else
  Msgbox LCase$(cmd)
End If

Answer:

GoTo would work well, I think.

Select Case cmd

    Case "ONE"
        MsgBox "one"
        GoTo AfterONE:

    Case "TWO"
AfterONE:
        MsgBox "two"

    Case "THREE"
        MsgBox "three"

End Select

It works; I tested it.

Answer:

I also had this problem recently.

I found the most readable and scale-able solution was to create a basic state-machine.

Simply wrap the Select in a While and end each case with which case is next.

While cmd <> ""
Select Case cmd
    Case "ONE"
        MsgBox  "one"
        cmd = "TWO"
    Case "TWO"
        MsgBox  "two"
        cmd = ""
    Case "THREE"
        MsgBox  "three"
        cmd = ""
End Select
Wend