How To Find Multiple Occurrences of a String in a RichTextBox (176643)
The information in this article applies to:
- Microsoft Visual Basic Learning Edition for Windows 5.0
- Microsoft Visual Basic Learning Edition for Windows 6.0
- Microsoft Visual Basic Professional Edition for Windows 5.0
- Microsoft Visual Basic Professional Edition for Windows 6.0
- Microsoft Visual Basic Enterprise Edition for Windows 5.0
- Microsoft Visual Basic Enterprise Edition for Windows 6.0
- Microsoft Visual Basic Standard Edition, 32-bit, for Windows 4.0
- Microsoft Visual Basic Professional Edition, 16-bit, for Windows 4.0
- Microsoft Visual Basic Professional Edition, 32-bit, for Windows 4.0
- Microsoft Visual Basic Enterprise Edition, 16-bit, for Windows 4.0
- Microsoft Visual Basic Enterprise Edition, 32-bit, for Windows 4.0
This article was previously published under Q176643 SUMMARY
Finding a single occurrence of a text string in a RichTextBox is fairly
straightforward. The Instr() function was designed for this. In order to
find multiple occurrences of a block of text, however, you need to write a
routine that will call the Instr() function as many times as necessary to
search the entire block of text for the desired string, while progressively
moving the starting point of the search forward to avoid finding the same
occurrence multiple times.
You can accomplish this by using a recursive routine, which calls itself
from within its own code. If you are not careful, however, recursion can
cause problems, such as infinite loops and stack faults. But recursion does
allow for elegant solutions to otherwise difficult situations.
This article illustrates recursion by example. The FindIt() routine calls
itself recursively as long as the return value of the Instr() function does
not equal zero. If this value is non-zero, it means Instr() found another
occurrence of the string it was looking for. If the value is zero, either
the string is not contained in the block of text being searched or all
occurrences of the string have already been found. Checking this value each
time the routine runs prevents an endless loop.
Modification Type: | Minor | Last Reviewed: | 7/1/2004 |
---|
Keywords: | kbhowto KB176643 |
---|
|