Thursday, May 28, 2020

A Reverse Find function for Excel

Sometimes you need to find the last instance of a string found in another string, you might need the integer that represents the character number of the beginning of that string.   This function is a great example of using a reverse for (step -1).  Check out the code below:

Public Function revfind(findwhat As String, infield As String) As Integer
revfind = 0
For i = Len(infield) - Len(findwhat) To 1 Step -1
    Debug.Print Mid(infield, i, Len(findwhat))
    If Mid(infield, i, Len(findwhat)) = findwhat Then
        revfind = i
        Exit For
    End If
Next
End Function
'You need to test this function, here is an implementation
Public Sub testrevfind()
Dim fw As String
Dim infield As String
fw = "-"
infield = "test-text-need-to-find-last-word"
t = revfind(fw, infield)
Debug.Print t
Debug.Print Left(infield, t - 1)
End Sub
'You should get this 
' 28 
' test-text-need-to-find-last






No comments:

Post a Comment