Since you want to just find the 2nd occurance it is easy... What if you want to find the 25th occurance????
I have written a small function... Try it out...
Requirement: 1 form, 1 RTB, 1 Command
Code:Option Explicit Dim Ret Private Sub Command1_Click() '-- usage '-- FindText(RichTextBox1, Search String, nth occurance) '-- Will find and color the 3rd occurance Ret = FindText(RichTextBox1, "Sid", 3) End Sub Private Function FindText(Rich As RichTextBox, sFindString As String, Numb As Integer) Dim FoundStrpos As Long, FoundStrLen As Long, CurInitStart As Long Dim CurInitLen As Long, count As Integer, lColor As Long '-- Color Green lColor = vbGreen '-- Save the cursor's current length and location CurInitStart = Rich.SelStart CurInitLen = Rich.SelLength '-- Length of the string to find FoundStrLen = Len(sFindString) '-- Find the first match FoundStrpos = Rich.Find(sFindString, 0, , rtfNoHighlight) If FoundStrpos > -1 Then Rich.SelStart = FoundStrpos Rich.SelLength = FoundStrLen count = count + 1 End If While FoundStrpos > -1 '-- Exception -- if you want to JUST find the first occurance If Numb = 1 Then '-- if found then color Rich.SelColor = lColor '-- Assign any number below -1 to get out of loop FoundStrpos = -2 ElseIf count > 0 And count < Numb Then 'Attempt to find the next match FoundStrpos = Rich.Find(sFindString, _ FoundStrpos + FoundStrLen, , rtfNoHighlight) Rich.SelStart = FoundStrpos Rich.SelLength = FoundStrLen '-- if found then color If count = (Numb - 1) Then Rich.SelColor = lColor '-- Increment Count count = count + 1 Else '-- Assign any number below -1 to get out of loop FoundStrpos = -2 End If Wend '-- Restore the cursor to its original status Rich.SelStart = CurInitStart Rich.SelLength = CurInitLen End Function




Reply With Quote