如何通过Excel VBA中的Select Case?

时间:2009-10-12 21:01:15

标签: vba excel-vba office-2007 excel

鉴于

Select Case cmd

    case "ONE":   MsgBox "one"

    case "TWO":   MsgBox "two"

    case "THREE": MsgBox "three"

End select

我的要求是cmd = "ONE"我需要"one"然后显示"two"但是目前我显示的是"one",然后该程序突破了选择的情况。 ..

8 个答案:

答案 0 :(得分:15)

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

    case "THREE": MsgBox "three"

End select

答案 1 :(得分:3)

有些人可以做这个工作:

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

答案 2 :(得分:2)

你必须做很长的事情。

Select Case cmd

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

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

    case "THREE": MsgBox "three"

End select

答案 3 :(得分:0)

这是设计上的。 http://msdn.microsoft.com/en-us/library/ee177199%28PROT.10%29.aspx

您可以尝试使用'goto'或过程调用来解决它。

答案 4 :(得分:0)

为什么要使用Select Case?你所要做的就是打印“cmd”值的小写版本。

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

答案 5 :(得分:0)

GoTo会很好用,我想。

Select Case cmd

    Case "ONE"
        MsgBox "one"
        GoTo AfterONE:

    Case "TWO"
AfterONE:
        MsgBox "two"

    Case "THREE"
        MsgBox "three"

End Select

有效;我测试了它。

答案 6 :(得分:0)

我最近也遇到过这个问题。

我发现最具可读性和可扩展性的解决方案是创建一个基本的状态机。

只需将Select打包在While中,然后结束下一个案例的每个案例。

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

答案 7 :(得分:0)

在非空情况下的“ Fall through”是C / C ++中错误的重要来源,因此不能在大多数其他语言(包括VBA)中实现。因此,如其他地方所述,请长距离操作并考虑过程调用以避免重复。

但是,如果像我一样,您因为不记得如何进行插入而最终出现在此页面上,那么可以接受的答案略有不同就是您可以(与所有VBA的命令)使用下划线表示继续到下一行:

Select Case cmd
Case "ONE", _
     "TWO":   
    if cmd = "ONE" Then MsgBox "one"
    MsgBox "two"
Case "THREE":
    MsgBox "three"
End select