This is an expansion of your idea to use Join
and InStr
:
Sub TestArraySearch()
Dim A(4) As String
A(0) = "First"
A(1) = "Second"
A(2) = "Third"
A(3) = "Fourth"
A(4) = "Fifth"
Debug.Print FastArraySearch(A, "Fi")
Debug.Print FastArraySearch(A, "o")
Debug.Print FastArraySearch(A, "hird")
Debug.Print FastArraySearch(A, "Fou")
Debug.Print FastArraySearch(A, "ndTh")
Debug.Print FastArraySearch(A, "fth")
End Sub
Function FastArraySearch(SearchArray As Variant,SearchPhrase As String) As String
Dim Pos As Long, i As Long, NumCharsProcessed As Long, Txt As String
Pos = InStr(Join(SearchArray, "§"), SearchPhrase)
If Pos > 0 Then
For i = LBound(SearchArray) To UBound(SearchArray)
NumCharsProcessed = NumCharsProcessed + Len(SearchArray(i)) + 1
If NumCharsProcessed >= Pos Then
FastArraySearch = SearchArray(i)
Exit Function
End If
Next i
End If
End Function
I did not benchmark it, but it should be quicker than doing a separate search each time through the loop. It searches once, then just adds up the string lengths until it gets to where the match was. Because the length of the string is stored before any of the characters in the string, the Len
function is highly optimized.
If this performance is still unacceptable I think you will need to find a different data structure than an array (eg, a disconnected recordset, as @Remou suggested).