8

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

2
  • Quicker in terms of less characters or efficiency of code? Commented Jul 9, 2013 at 16:45
  • @mehow Less characters. My list will have less than 10 numbers to check, so performance differences between methods should be negligible. Commented Jul 9, 2013 at 16:48

5 Answers 5

11

An alternative would be:

select case userID
    case 1,2,3,4,5,6
       ' do something
end select

It conveys very good the meaning of the if ... then ... else construct.

Sign up to request clarification or add additional context in comments.

Comments

5

Another way

If UBound(Filter(Array(1, 2, 3, 4, 5, 6), UserID)) > -1 Then

Filter returns an array with the match. If there's no match, ubound = -1.

Comments

4

You can use the Application.Match function on an array:

If Not IsError(Application.Match(userID, Split("1,2,3,4",","))) Then...

2 Comments

Doesn't IsError need () in this usage?
Yes, it does. Good catch. I have revised.
0

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

Comments

0

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!"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.