Jonmo1
MrExcel MVP
- Joined
- Oct 12, 2006
- Messages
- 44,061
Re: June/July 2008 Challenge of the Month
OK, last one I promise...
After further consideration, I changed a rule in the UDF.
With the Nth option, it was set to use the Last Match if Nth was larger then the # of Matches Found. In other words, in this sentence..
The blue ocean has a red boat in it.
If you put 3 or higher as the Nth, it would have used red. Even though red was only the 2nd color in the sentence.
I now think that would probably be a bad idea, it could be misleading to think there is a 3rd color in the sentence when there actually isn't....so I changed it to return blank in that case instead...
OK, last one I promise...
After further consideration, I changed a rule in the UDF.
With the Nth option, it was set to use the Last Match if Nth was larger then the # of Matches Found. In other words, in this sentence..
The blue ocean has a red boat in it.
If you put 3 or higher as the Nth, it would have used red. Even though red was only the 2nd color in the sentence.
I now think that would probably be a bad idea, it could be misleading to think there is a 3rd color in the sentence when there actually isn't....so I changed it to return blank in that case instead...
Code:
Public Function Jonmo1(C As Range, L As Range, Optional Nth As Long = 1, _
Optional Fuzzy As Boolean = False) As String
Dim MyArray As Variant
Dim Pos() As Variant
Dim Word() As Variant
Dim MyRange As Range
Dim r As Range
Dim counter As Long, X As Long, Y
Set MyRange = Range(L(1, 1), L(L.Rows.Count, 1).End(xlUp).Offset(0, L.Columns.Count - 1))
If Fuzzy = False Then
MyArray = Split(Replace(C, Chr(160), ""))
For X = LBound(MyArray) To UBound(MyArray)
Y = Application.Match(MyArray(X), MyRange.Columns(1), 0)
If Not IsError(Y) Then
counter = counter + 1
If counter = Nth Then
Jonmo1 = MyRange(Y, 2)
Exit For
End If
End If
Next X
Else
For Each r In Range(MyRange.Columns(1).Address)
X = InStr(1, C, r)
If X > 0 Then
counter = counter + 1
ReDim Preserve Pos(1 To counter)
ReDim Preserve Word(1 To counter)
Pos(counter) = X
Word(counter) = r
End If
Next r
If counter < 1 Then Exit Function
If Nth > UBound(Pos) Then Exit Function
X = Application.Small(Pos, Nth)
Jonmo1 = Application.VLookup(Word(Application.Match(X, Pos, 0)), MyRange, 2, 0)
End If
End Function