Article ID: 176643
Article Last Modified on 7/1/2004
Private Sub Form_Load()
'Edit the following line to point to your license.txt or another
'text file
RichTextBox1.LoadFile "license.txt"
End Sub
Private Sub Command1_Click()
Dim strval As String 'Inputbox returns a string
Dim nStrings As Long
'Reload the file to undo the previous selections
'Edit the following line to point to your license.txt or another
'text file
RichTextBox1.LoadFile "license.txt"
'Ask the user what string to find. Defaults to finding all
'occurrences of the word "the." In this example, you are
'concatenating spaces onto each end of the search string to
'prevent the FindIt routine from finding occurrences of the
'search string within other words, ie; finding "the" in "there"
'or "these." If you want to find the string within other strings,
'simply eliminate the concatenation.
strval = " " & InputBox("Enter the string to find.", "Findit", _
"the") & " "
If strval <> "" Then
'the user didn't click cancel call the FindIt routine
'and pass it the
nStrings = FindIt(RichTextBox1, strval)
MsgBox (Str$(nStrings) & " instances found.")
End If
End Sub
'********************************************************************
'Findit takes three arguments; two required, and one optional. The
'required arguments, Box and Srch, are a RichTextBox object and a
'string to search for. The optional argument, Start, is a Long
'integer that is used in the recursive calls.
'********************************************************************
Private Function FindIt(Box As RichTextBox, Srch As String, _
Optional Start As Long)
Dim retval As Long 'Instr returns a long
Dim Source As String 'variable used in Instr
Source = Box.Text 'put the text to search into the variable
If Start = 0 Then Start = 1 'the initial call doesn't pass a value
'for Start, so it will equal 0
retval = InStr(Start, Source, Srch) 'do the first search,
'starting at the beginning
'of the text
If retval <> 0 Then 'there is at least one more occurrence of
'the string
'the RichTextBox doesn't support multiple active selections, so
'this section marks the occurrences of the search string by
'making them Bold and Red
With Box
.SelStart = retval - 1
.SelLength = Len(Srch)
.SelColor = vbRed
.SelBold = True
.SelLength = 0 'this line removes the selection
'highlight
End With
Start = retval + Len(Srch) 'move the starting point past the
'first occurrence
'FindIt calls itself with new arguments
'this is what makes it Recursive
FindIt = 1 + FindIt(Box, Srch, Start)
End If
End Function
Additional query words: Recursive Recursion Multiple Selection Richtextbox RTF KBCONTROL
Keywords: kbhowto KB176643