rajat_magic
Board Regular
- Joined
- Sep 22, 2003
- Messages
- 57
Is there a function in VBA that can establish whether a particular value is part of an array, or is it necessary to actually cycle through all of the values and check individually?
n = 0
test = 10
Do Until n > z
If varData(n) = test Then
MsgBox "Match in Row " & n + 2
Exit Sub
End If
n = n + 1
Loop
[COLOR=Green] 'Initialise Array[/COLOR]
[COLOR=RoyalBlue]Dim [/COLOR]myArray(2) [COLOR=RoyalBlue]As String[/COLOR]
myArray(0) = "Value1"
myArray(1) = "Value2"
myArray(2) = "Value3"
[COLOR=SeaGreen] 'Initialise Search Term[/COLOR]
[COLOR=RoyalBlue]Dim [/COLOR]searchTerm [COLOR=RoyalBlue]As String[/COLOR]
searchTerm = "Value2"
[COLOR=SeaGreen]'Check if a value exists in the Array[/COLOR]
[COLOR=RoyalBlue]If UBound[/COLOR](Filter(myArray, searchTerm)) >= 0 [COLOR=RoyalBlue]And [/COLOR]searchTerm <> ""[COLOR=RoyalBlue] Then[/COLOR]
MsgBox ("Search Term SUCCESSFULLY located in the Array")
[COLOR=RoyalBlue]Else[/COLOR]
MsgBox ("Search Term could NOT be located in the Array")
[COLOR=RoyalBlue]End If[/COLOR]
Dim C As String, FindMe As String, myArray() As Variant
Dim ItemFound As Boolean, MatchCase As Boolean
' Load dynamic Variant array in a single line of code
myArray = Array("Value1", "Value2", "Value3")
' Initialize search options
FindMe = "value2"
MatchCase = False
' Perform search
C = Chr$(1)
ItemFound = InStr(1, C & Join(myArray, C) & C, C & FindMe & C, 1 + MatchCase)
' Display result
If ItemFound Then
MsgBox "Found it!"
Else
MsgBox "Could NOT find it."
End If
Here is a non-looping method that avoids the partial match problem that the Filter function opens one up to...
The above code only finds whole array element matches; that is, if you searched for "Val", it would not match any elements in the array (the Filter function method would produce a match). I also provided a MatchCase Boolean variable to control whether the letter casing must be exact or not when performing the search.Code:Dim C As String, FindMe As String, myArray() As Variant Dim ItemFound As Boolean, MatchCase As Boolean ' Load dynamic Variant array in a single line of code myArray = Array("Value1", "Value2", "Value3") ' Initialize search options FindMe = "value2" MatchCase = False ' Perform search C = Chr$(1) ItemFound = InStr(1, C & Join(myArray, C) & C, C & FindMe & C, 1 + MatchCase) ' Display result If ItemFound Then MsgBox "Found it!" Else MsgBox "Could NOT find it." End If