How to check against a list of values in an IF statement?

You could make a list of numbers, and then in a for-loop to compare these:

dim newNumber as Integer
dim compareList as new List Of(int)

for count as integer = 0 to compareList.count - 1
    if newNumber = compareList(nCount)
       'Do Stuff
    end if
next

This is a simple way of doing that I like to do, but may get performance intensive if your lists are really large/you want to do a lot of code in the "if" loop.


You can use a Select Case statement:

select case var
case 1,4,5,6,12
  'do something
case else
  'alternative
end select

I'm a bit late to the 'party' but how about:

If InStr(1, ",1,5,8", "," & lVal1, vbTextCompare) > 0 Then

to check if 'lVal1' to equal to 1, 5 or 8.

And

If InStr(1, ",6,8,10,12", "," & lVal2, vbTextCompare) = 0 Then

to check that 'lVal2' is not equal to 6, 8, 10, 12.

The comma delimiters are important because, without them, in the first example, '15' or '58' or '158' would all be matched if 'lVal' was able to take one of those values.

You will need to pay attention to the delimiter that you use if there was likely to be any ambiguity with the value being checked for.

Likewise, using your knowledge of the range of values that will be encountered, the clunkiness of the leading delimiter in the first string and concatenating the delimiter to the front of the search value, could be removed.