PDA

View Full Version : Solved: Select Case with > 1 Variable



philfer
11-05-2009, 04:48 AM
Hello,

Is it possible to create a SELECT CASE statement with more than one variable, for example something like :-

SELECT CASE height, width

CASE height > 25 AND height < 50, width > 10 AND width < 100
'do something

etc
etc

END SELECT

does anyone have any code examples of this working in practice

Thanks everyone
Phil

Oorang
11-09-2009, 10:04 AM
Well sort of.
Select Case True
Case height > 10 And width < 20
Case height > 15 And Width < 40
Case Else
End Select
But if you are doing complex conditions this is a real chance for a logical error that won't get caught until runtime.
A few other tips:
Take the time to set up a truth table and carefully make sure your logic covers all possibilities.
Structure your code to run through all possibilities with the fewest possible conditional checks for each branch of the logic tree.
Make sure your logic is structured in such a way that if a scenario "falls through" your checks (no condition is true), you still catch it and handle it.
And finally... Make sure you explain yourself in the comments.

GreenTree
11-09-2009, 05:25 PM
Sounds like a good use for if... elseif ... elseif... else.


If ht > 10 and ht < 100 and wd > 5 and wd < 20 then
'whatever
elseif ht < 10 and wd < 5 then
'whatever
elseif ht > 100 and wd > 20 then
' whatever
else
' unreasonable / unexpected condition! Alert the user
end if


Totally agree with Aaron's cautions about thinking things out carefully ahead of time, and alerting the user if something unexpected or "impossible" occurs... the "else" condition that you never expect to see, which flags the error, for instance.

G.T.

Paul_Hossler
11-09-2009, 06:35 PM
Another option (longer in code, but easier to follow [IMHO]) is something like this

Doesn't use Select/Case like asked in the first post, but as the others pointed out, for complex conditions there can be a few gotcha's


If ht <= 10 then
If wd <= 20 then
'code -------
elseif wd <= 100 then
'code ----
else
Msgbox "Ht <= 10, but wd > 100"
end if

elseif ht <= 100 then
If wd <= 20 then
'code -------
elseif wd <= 100 then
'code ----
else
Msgbox "Ht <= 100, but wd > 100"
end if

else
Msgbox "Ht > 100'
end if


I did notice that Less Than was used, but if there's a chance that ht might = 10, you'd need to handle that also

Paul