user1488660
user1488660

Reputation: 65

How to use a Select statement with an Array of Options

I want to remotely/reusable store a Case statement multi-value ExpressionList.

Is there a way to feed a remote List into a Case (array was my only thought).

This is normal:

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

But these case lists are used a lot and I want to move them to a central location. So I want something more like, (and not have to rework code in hundreds of places).

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

If the case's were just a lot singles cases it would just work with variables, but I need it to be a list as the amount may change as seen in the above 'wanted' example[grape]. I am trying to retain the existing Case statements and not convert to lots of Ifs and For loops (there's many more cases than two).

Upvotes: 1

Views: 108

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200323

You could create a dictionary mapping items to their respective type

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"

and then do a simple lookup:

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

Upvotes: 4

Related Questions