You can find text in the Rich Text box control very easily using the Find Method. The Find Method uses the following syntax:
RichTextBox1.Find FindString, StartPos, EndPos,
Options
FindString is the Text to fine. StartPos is an integer representing the start position. To start from the beginning of the document this would be set to 0. EndPos is an integer representing the end position. If this is left blank then it is set the the length of the document. Options contains one or more of the following flags:
Flag | Action |
rtfNoHighlight | Don't highlight selection |
rtfWholeWord | Only searches for the whole word |
rtfMatchCase | Matches the case of the FindString |
The following code searches RichTextBox1 for the Text contained in Text1. It searched for the whole word only:
Sub Command1_Click()
SearchText = Text1.Text
gOptions = rtfWholeWord
Result = RichTextBox1.Find (SearchText,0, ,gOptions)
If Result = -1 Then
Msgbox "Text not found"
Else
Msgbox "Text Found"
End If
End Sub
Once you have found the text, you can change it using the SelText property. The following code will search the whole of RTB1 for the text contained in txtFind, and then will replace that text with the text in txtReplace. It uses Match Case and Whole Word Only.
' Set the options
gOptions = rtfWholeWord + rtfMatchCase
' Set the counter to 0
gCount = 0
Do
If gDoc.Find(txtFind.Text, RTB1.SelStart + RTB1.SelLength,
, goptions) = -1 Then
' No more matches
If gCount = 0 Then
' First time
round, no matches found
MsgBox "Unable
to find '" & txtFind.Text & "' in specified range"
Else
' Matches
found
MsgBox "The
specified region has been searched. " & gCount & _
" replacements have been made"
End If
cmdFind.Caption = "&Find"
Exit Do
Else
' Increment replace count
gCount = gCount + 1
' Replace the selected text with
the replace text
gDoc.SelText = txtReplace.Text
End If
Loop
Comments