Check if a value is in an array or not with Excel VBA
I've got some code below, that is supposed to be checking if a value is in an Array or not.
Sub test()
vars1 = Array("Examples")
vars2 = Array("Example")
If IsInArray(Range("A1").Value, vars1) Then
x = 1
End If
If IsInArray(Range("A1").Value, vars2) Then
x = 1
End If
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
If the cell A1
contains the word Examples
for some reason both of the IsInArray
detects it as existing for both Arrays when it should only find it existing in the vars1
array
What do I need to change to make my IsInArray
function to make it an exact match?
You can brute force it like this:
Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Dim i
For i = LBound(arr) To UBound(arr)
If arr(i) = stringToBeFound Then
IsInArray = True
Exit Function
End If
Next i
IsInArray = False
End Function
Use like
IsInArray("example", Array("example", "someother text", "more things", "and another"))
This Question was asked here: VBA Arrays - Check strict (not approximative) match
Sub test()
vars1 = Array("Examples")
vars2 = Array("Example")
If IsInArray(Range("A1").value, vars1) Then
x = 1
End If
If IsInArray(Range("A1").value, vars2) Then
x = 1
End If
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
I searched for this very question and when I saw the answers I ended up creating something different (because I favor less code over most other things most of the time) that should work in the vast majority of cases. Basically turn the array into a string with array elements separated by some delimiter character, and then wrap the search value in the delimiter character and pass through instr.
Function is_in_array(value As String, test_array) As Boolean
If Not (IsArray(test_array)) Then Exit Function
If InStr(1, "'" & Join(test_array, "'") & "'", "'" & value & "'") > 0 _
Then is_in_array = True
End Function
And you'd execute the function like this:
test = is_in_array(1, array(1, 2, 3))
Use Match() function in excel VBA to check whether the value exists in an array.
Sub test()
Dim x As Long
vars1 = Array("Abc", "Xyz", "Examples")
vars2 = Array("Def", "IJK", "MNO")
If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
x = 1
ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
x = 1
End If
MsgBox x
End Sub