2

I'm new so sorry if this is a dumb question. I want to have an If statement stating if variable a is an element of a set of some integers then... Would it work if I write:

If a=1,6,12,19 Then

or would I have to write

If a=1 Or a=6 Or a=12 Or a=19 Then

3
  • Did you try it? Commented Mar 17, 2017 at 19:43
  • 1
    You can use a case statement. E.g. Public Function test(a) Select Case a Case 1, 2, 3, 4, 5, 6 'do something End Select End Function Commented Mar 17, 2017 at 19:46
  • 1
    Possible duplicate of VBA equivalent to SQL 'in' function Commented Mar 17, 2017 at 19:54

3 Answers 3

4

No, you can't write it as if a=1,6,12,19 Then but there are some alternatives that you can use and they are covered in the answers to this previous question. This is the one that I'd recommend in most cases.

select case userID
    case 1,2,3,4,5,6
       ' do something
end select
Sign up to request clarification or add additional context in comments.

1 Comment

If there are ever anything more than 2 conditions, I always go with select case. It's a beautiful thing! Don't forget case else. It's not required but it's a good habit to stick it in there before your end select so you don't forget the option is there :)
1

The InStr function can handle it as a delimited substring within a string containing delimited options.

if cbool(instr(1, "x1x2x3x4x5x6x", format(a, "x0x"))) then
    'a is a number between 1 and 6
    debug.Print a & " is in 1,2,3,4,5,6"
end if

Comments

0

you can use Application.Match() method

if Not IsError(Application.Match(a,array(1,6,12,19),0) Then
    your code
End If

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.