模仿"IN"运算符

All*_*owe 24 excel vba operators excel-vba in-operator

如何实现:

if X in (1,2,3) then
Run Code Online (Sandbox Code Playgroud)

代替:

if x=1 or x=2 or x=3 then
Run Code Online (Sandbox Code Playgroud)

换句话说,如何才能最好地模仿INVBA中的运算符for excel?

Kre*_*dns 15

我不认为有一个非常优雅的解决方案.

但是,您可以尝试:

If Not IsError(Application.Match(x, Array("Me", "You", "Dog", "Boo"), False)) Then
Run Code Online (Sandbox Code Playgroud)

或者你可以编写自己的函数:

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
Run Code Online (Sandbox Code Playgroud)


Rob*_*rns 13

您也可以尝试使用CASE语句而不是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
Run Code Online (Sandbox Code Playgroud)


ash*_*awg 8

最快的方法:

这是一种比任何其他答案更快、更紧凑的方法,并且适用于数字或文本值:

Function IsIn(valCheck, valList As String) As Boolean  
    IsIn = Not InStr("," & valList & ",", "," & valCheck & ",") = 0
End Function
Run Code Online (Sandbox Code Playgroud)

例子:

IsIn与数值一起使用:

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
Run Code Online (Sandbox Code Playgroud)

使用IsIn带有字符串值:

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
Run Code Online (Sandbox Code Playgroud)

速度比较:

为了比较速度,我从接受的答案中运行了 100,000 次测试:

  • 0.406 sec (FASTEST) 这个函数(使用InStr):
  • 1.828 sec (450% slower)使用“ISIN”功能 接受的答案
  • 1.799 sec (440% slower) 答案与freeVBcode的“IsInArray”
  • 0.838 sec (206% slower) 使用修改后的“IsInArray”函数 回答

我没有包括使用的更长的答案SELECT..CASE因为与“ ”相比,OP 的目标大概是简化和缩短任务if x=1 or x=2 or x=3 then