views:

521

answers:

5
+3  Q: 

vba "IN" operator

How best can one imitate the "IN" operator in VBA for excel?

eg

if X in (1,2,3) then

instead of:

if x=1 or x=2 or x=3 then

???

+2  A: 

I don't think there is a very elegant solution.

However, you could try:

If Not IsError(Application.Match(x, Array("Me", "You", "Dog", "Boo"), False)) Then

or you could write your own function:

Function ISIN(x, StringSetElementsAsArray)
    ISIN = InStr(1, Join(StringSetElementsAsArray, Chr(0)), _
    x, vbTextCompare) > 0
End Function

Sub testIt()
    Dim x As String
    x = "Dog"
    MsgBox ISIN(x, Array("Me", "You", "Dog", "Boo"))
End Sub
Lucas McCoy
+2  A: 

did you try

eval("3 in(1,2,3,4,5)")
THEn
This should work.
Nissan Fan
I get "sub or function not defined" - don't know if this is because I am in VBA (not VB ) ? have edited the question...
Bazil
It is Access VBA function. Sorry I didn't see that you mentioned excel VBA.
THEn
+1  A: 

There's none that I'm aware of.

I usually use a home-brewed InArray() function like the one at http://www.freevbcode.com/ShowCode.asp?ID=1675

You could also make a version that iterates through the array instead of concatenating, if that is more appropriate to your data type.

anschauung
+2  A: 

You could also try the CASE statement instead of IF

Select Case X

 Case 1 To 3   
  ' Code to do something
 Case 4, 5, 6
  ' Code to do something else
 Case Else  
  ' More code or do nothing

End Select
Robert Mearns
+1  A: 

You can also use the Filter function as described here

Jon Fournier