Using logical operators in a Select Case Statement

M

Mota

Hi;
Is there a way to use operators such as "AND" or "OR" or "Between" in a
Select Case statement?
For example,how can we do such a meaning in VBA?
Dim X as Integer
X=800
Select Case X
Case X>0 And X<500 ' This is a wrong Syntax and causes to
"CaseElse"happenes,
' untill we replace it with
"Case Is > 0"
DoSomething.....

Case X>=500 And X<1000
DoSomethingElse.....
Case Else
MsgBox "Wrong Data Entered"
End Select

For now,im doing this thru an If statement after each "Case".Isnt there a
syntax to do limitation on each "Case",without putting an If after it?
Thank you.
 
C

Cheryl Fischer

The following air-code examples may work for you:

Select Case X
Case 126 to 500
' any number between 126 and 500
Case 5, 9, 125
' 5 or 9 or 125
Case is > 800
' any number greater than 800
Case Else
'
End Select
 
M

Marshall Barton

Mota said:
Is there a way to use operators such as "AND" or "OR" or "Between" in a
Select Case statement?
For example,how can we do such a meaning in VBA?
Dim X as Integer
X=800
Select Case X
Case X>0 And X<500 ' This is a wrong Syntax and causes to
"CaseElse"happenes,
' untill we replace it with
"Case Is > 0"
DoSomething.....

Case X>=500 And X<1000
DoSomethingElse.....
Case Else
MsgBox "Wrong Data Entered"
End Select

Case has quite a few options that you can use.

The value can be checked against a range by using TO

X Between 10 And 13
would be:
Select Case X
Case 10 To 13

or, for general relational operators use the IS keyword:

X >= 31
would be:
Case Is >= 31

Note that using a list of values is the equivalent of OR

X=10 Or X=20
would be written:
Case 10, 20

and all of the above can be combined:

(X Between 10 And 13) Or (X = 20) Or (X >= 31)
would be:
Case 10 To 13, 20, Is >= 31

Be sure to read Help for all the syntax choices.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top