Home » excel » Excel VBA IN keyword

Excel VBA IN keyword

Posted by: admin April 23, 2020 Leave a comment


Is there a better way to code this in VBA:

If x = 'a' or x = 'b' or x ='c' or x = 'd' then
End if

The IN keyword would come very handy here:

If x IN ('a','b','c','d') then
End If

–> but VBA doesn’t recognise IN. Is there an alternative keyword to it in the syntax?
Thank you!

How to&Answers:

The purpose of the FILTER() function is to see if an item appears in an array:

Sub FilterExample()
    ary = Split("a,b,c,d", ",")
    x = "b"
    If Filter(ary, x)(o) <> "" Then
        MsgBox "match found"
    End If
End Sub


Gary’s Student’s answer in its current form will cause an error when a match is not found. I believe the following is better:

x = "a"
If UBound(Filter(Array("a", "b", "c", "d"), x)) > -1 Then
    MsgBox "Match found"
End If

I do comment though that when x is an empty string the filter function returns the whole array. So if x is an empty string the above will always return a match. The below accounts for this

x = "a"
If UBound(Filter(Array("a", "b", "c", "d"), x)) > -1 And x <> vbNullString Then
    MsgBox "Match found"
End If