NthMatch is Custom UDF made by me to overcome the cons of Match Function and Array formulas.
NthMatch function provides the row no. of the Nth match in a range, say in the given example, it is providing the Row No ie. 7 for the third Match of "Sachin" in the Range. The Reason I made this formula is that the Match Function provides only the first match and also it needs a lot to skill for a lay man to write an array formula to do the same job. As you can see in the above picture, Both functions gives the same results but the NthMatch syntax is much shorter and easier to understand than array formula.
Syntax:-
=NthMatch(Lookup_Value, Lookup_Range, Match No.)
Here are the codes:-
Ist Code:-
2nd Code:-
Function NthMatchE(ByVal Lvalue As Variant, ByVal Lrange As Variant, Mnum As Variant)
f = "SMALL(IF(" & Lrange.Address & "=""" & Lvalue & """,ROW($1:" & Lrange.Rows.Count & "))," & Mnum & ")"
NthMatchE = Evaluate(f)
End Function
2nd Code:-
Function NthMatch(ByVal Lvalue As Variant, Lrange As Variant, Mnum As Variant)
Mstr = "|" & Join(Application.Transpose(Lrange), "|")
Lvalue = "|" & Lvalue
Start = 0
For c = 1 To Mnum
Start = InStr(Start + 1, Mstr, Lvalue)
If Start = 0 Then NthMatch = "#N/A": GoTo 0 'This the line which I have included to leave loop.
Next
Temp = Left(Mstr, Start)
NthMatch = Len(Temp) - Len(Replace(Temp, "|", "")) 'Calculating Row No.
0
End Function
The First one is Faster of the two. Because it is as good as making same array formula run through VBA. The second one is just for the Knowledge base that how it can be achieved using String Manipulation.
I wanna mention here that Array alternative is faster than all but using Evaluate function with a UDF makes it more understandable and easy to use. If you know Arrays then I will prefer going with them.
Regards,
Vikas Gautam
Vikas Gautam
Comments
Post a Comment