I'm writing a conditional statement in vba like
if(userID = 1 or userID = 2 or userID = 3 or userID = 4) then
...
I was wondering if there's a quicker, cleaner way to do this. Something like
if(userID in (1,2,3,4)) then
...
Thanks
I'm writing a conditional statement in vba like
if(userID = 1 or userID = 2 or userID = 3 or userID = 4) then
...
I was wondering if there's a quicker, cleaner way to do this. Something like
if(userID in (1,2,3,4)) then
...
Thanks
You can use the Application.Match function on an array:
If Not IsError(Application.Match(userID, Split("1,2,3,4",","))) Then...
IsError need () in this usage?CW because this matches the hypothetical example, but not likely a real use situation. However, Like is a good keyword to know.
If userID Like "[1-6]" Then
This is ok for single digit checks, but not real world multi-character user IDs.
i.e.
userID = 1
If userID Like "[1-6]" Then ' result is True
but
userID = 11
If userID Like "[1-6]" Then ' result is False
You could make a basic function like this:
Function InArray(Match, SourceArray)
InArray = False
For i = LBound(SourceArray) To UBound(SourceArray)
If SourceArray(i) = Match Then
InArray = True
Exit Function
End If
Next
End Function
Then you could say:
if InArray(userId, array(1,2,3,4)) then msgbox "Found it!"