0

Find the Nth occurrence of character/string

Many a times we need to do some stuff which is non conventional and its a challenge to solve such a problem.

I had come across a situation in Excel where I needed to find the Nth occurrence of character in a string. I looked for solutions and finally wrote my own function

Function FindNthLocation(StrtoFind As String, SourceStr As String, N As Integer) As Integer
    Dim J As Integer
    Application.Volatile
    FindNthLocation = 0
    For J = 1 To N
        FindNthLocation = InStr(FindNthLocation + 1, SourceStr, StrtoFind)
        If FindNthLocation = 0 Then Exit For
    Next
End Function

example

=FindNthLocation(“a”, “abcdabcd”,2)

will return 8

Neville Fernandes

Leave a Reply

Your email address will not be published. Required fields are marked *