Imitating the "IN" Operator

80,207

Solution 1

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

Solution 2

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
 Case 7
  ' Code to do something
 Case Else  
  ' More code or do nothing

End Select

Solution 3

Fastest Method:

Here's a method much faster and more compact than any of the other answers, and works with numeric or text values:

Function IsIn(valCheck, valList As String) As Boolean  
    IsIn = Not InStr("," & valList & ",", "," & valCheck & ",") = 0
End Function

Examples:

Use IsIn with a numeric value:

Sub demo_Number()
    Const x = 2
    If IsIn(x, "1,2,3") Then
        Debug.Print "Value " & x & " was Found!"
    Else
        Debug.Print "Value " & x & " was not Found."
    End If
End Sub

Use IsIn with a string value:

Sub demo_Text()
    Const x = "Dog"
    If IsIn(x, "Me,You,Dog,Boo") Then
        Debug.Print "Value " & x & " was Found!"
    Else
        Debug.Print "Value " & x & " was not Found."
    End If
End Sub

Speed Comparison:

To compare speed I ran the test from the accepted answer 100,000 times:

  • 0.406 sec (FASTEST) This Function (using InStr):
  • 1.828 sec (450% slower) Accepted Answer with the "ISIN" function
  • 1.799 sec (440% slower) Answer with the "IsInArray" from freeVBcode
  • 0.838 sec (206% slower) Answer with modified "IsInArray" function

I didn't include the much longer answer that uses SELECT..CASE since the OP's goal was presumably to simplify and shorten the task compared to "if x=1 or x=2 or x=3 then".

Solution 4

did you try

eval("3 in(1,2,3,4,5)")

Solution 5

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.

Share:
80,207
Allan Bowe
Author by

Allan Bowe

SAS Consultant Projects: https://sasjs.io - Framework for building web apps on SAS https://sasensei.com - quiz game for SAS https://datacontroller.io - data capture, governance & approval https://rawsas.com - SAS blog

Updated on July 31, 2022

Comments

  • Allan Bowe
    Allan Bowe over 1 year

    How can one achieve:

    if X in (1,2,3) then
    

    instead of:

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

    In other words, how can one best imitate the IN operator in VBA for excel?