为 RichTextBox 查找和查找下一个

Find and Find Next for RichTextBox

richTextBox1.Text = "Where there is a will there is way";

我只想更改两者 is 只有红色。

我知道如何更改第一个 is,但我不知道如何更改第二个 is

RichTextBox1.SelStart = RichTextBox1.Find("is")
RichTextBox1.SelLength = 2
RichTextBox1.SelColor = vbRed

根据 MSDN Article:

If the text searched for is found, the Find method highlights the specified text and returns the index of the first character highlighted. If the specified text is not found, the Find method returns 1.

我假设这是一个拼写错误,如果找不到文本,return 是 -1 而不是 1,因此,在您的代码中:

Dim idx As Integer 
Dim start As Integer

Do
    idx = RichTextBox1.Find("is", start) '// First time through start at beginning
    If idx = -1 Then Exit Do
    RichTextBox1.SelStart = idx
    RichTextBox1.SelLength = 2
    RichTextBox1.SelColor = vbRed
    start = idx + 1 '// Set the start for .Find to the next character
Loop
RichTextBox1.SelLength = 0 ' Clear the selection