首页 > 解决方案 > 如何使用带有选项数组的 Select 语句

问题描述

我想远程/可重用存储Case语句多值ExpressionList

有没有办法将远程列表馈送到一个Case(数组是我唯一的想法)。

这个是正常的:

Select Case(LCase(strProduce))
    Case "apple", "pear", "banana"
        'Do Frutie stuff
    Case "corn", "care-rot", "radish"
        'Do Vegitapole stuff (get the spelling reference?)
End Case

但是这些案例列表被大量使用,我想将它们移动到一个中心位置。所以我想要更多类似的东西(并且不必在数百个地方重新编写代码)。

aryFruit = Array("apple", "pear", "banana", "grape")
aryVegetable = Array("corn", "carrot", "radish")

Select Case(LCase(strProduce))
    Case In aryFruit
        'Do Fruit stuff
    Case In aryVegetable
        'Do Vegitapole stuff (get the spelling reference?)
End Case

如果案例只是很多单身案例,它只适用于变量,但我需要它是一个列表,因为数量可能会发生变化,如上面的“想要”示例[葡萄]所示。我试图保留现有的 Case 语句,而不是转换为大量的Ifs 和For循环(案例多于两个)。

标签: vbscript

解决方案


您可以创建一个字典,将项目映射到它们各自的类型

Set produce = CreateObject("Scripting.Dictionary")
produce.CompareMode = vbTextCompare

produce("apple")  = "fruit"
produce("pear")   = "fruit"
produce("banana") = "fruit"
produce("grape")  = "fruit"
produce("corn")   = "vegetable"
produce("carrot") = "vegetable"
produce("radish") = "vegetable"

然后做一个简单的查找:

Select Case produce(strProduce)
    Case "fruit"
        'Do fruit stuff
    Case "vegetable"
        'Do vegetable stuff
End Case

推荐阅读