在嵌套选择VB中具有单个案例

时间:2014-07-17 08:59:03

标签: vbscript

我的代码如下所示

Dim Msg As String

Select Item_name

Case "Fruit"

  Select Fruit_Name
      Case "Apple"
          //Do something
      Case "Orange"
          //Do something
      Case Else
          Msg="Erorr"
  End Select

Case "Vegitable"

        //Do something
Case Else
    Msg="Error"

End Select

我可以选择单个案例吗?因为两个案例都是相同的。如果是这样,我该如何实施?

1 个答案:

答案 0 :(得分:0)

VBScript :您可以在Case之后使用以逗号分隔的项目列表,将它们与Select Case后指定的值进行比较:

>> For Each Plant In Split("Apple Orange Cabbage Salad")
>>     Select Case Plant
>>        Case "Apple", "Cabbage"
>>          WScript.Echo "cook",  Plant
>>        Case "Orange"
>>          WScript.Echo "throw away", Plant
>>        Case Else
>>          WScript.Echo "feed to rabbit", Plant
>>     End Select
>> Next
>>
cook Apple
throw away Orange
cook Cabbage
feed to rabbit Salad

更新评论:

您可以将布尔表达式(Case)与True / False(Select Case)进行比较:

>> For Each Kind In Split("fruit vegetable")
>>     For Each Spec In Split("apple cabbage")
>>         Select Case True
>>            Case Kind = "fruit" And Spec = "apple"
>>              WScript.Echo Kind, Spec
>>            Case Kind = "vegetable" And Spec = "apple"
>>              WScript.Echo "surprise", Kind, Spec
>>         End Select
>>     Next
>> Next
>>
fruit apple
surprise vegetable apple

需要详细描述真实世界问题,以讨论嵌套If语句是否是更好的策略。

更新评论II:

使用decision table分析条件和隐含的操作。然后计划并实施“评估条件”树,根据需要使用If和/或Select Case来清楚地显示条件及其(相互)依赖关系。如果某些(组合)条件需要“相同”操作,请将它们放入Sub / Function。

(参见docs