Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

If Exists in a set 1

Status
Not open for further replies.

egodette

Technical User
Jun 12, 2002
222
US
Instead of using
If (variable = "one" or variable = "two" or variable = "three") then

Is there a way in VBA for Excel to say
If variable exists in ("one","two","three") then
 
Another way is to use a Case test. Very useful when you have lots of possibilities in different groups:
Code:
Dim StrVar As String
Select Case StrVar
  Case "one", "two", "three"
    'Do something
  Case "four", "five", "six"
    'Do something
  Case Else
    'Do something
End Select

Cheers
Paul Edstein
[MS MVP - Word]
 
How does one get a star for code that

a) doesn't work (at least not with VBA's Instr function);
b) if it did work in the way clearly expected would be prone to erroneous results?
 
A safer way:
Code:
If InStr(",one,two,three,", "," & variable & ",") > 0 Then

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
>Cut and paste got me

Yep! I've had that as well :)

And unsurprisingly PHV's solution fixes the error issue I was alluding to
 
How about using the array filter funtion and a check for negative first?
==>
Code:
ValidValues = Array("one", "two", "three")

'negative check
If UBound(Filter(ValidValues, variable, True, vbTextCompare)) = -1 Then 'not one, two nor three
    'do your stuff here
Else
    'you have one, two or three
    'do your stuff here
End If

Should do the trick as well, and "one,two" as variable would not hit. (In case that could ever happen)

Cheers,
MakeItSo

“Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family.” (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Nope, that's prone to the same errors as remou's solution (for example "on" would match), and which PHV's solution does not fall prey to.
 
Hmmm. I see.
Thanks for pointing out.

“Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family.” (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top