如何使用 InStr 函数在多行文本框中搜索和突出显示值?

How can I use the InStr function to search and highlight a value in a multiline textbox?

我正在尝试在多行文本框内创建一个搜索,该搜索将找到一个值的每个实例并在文本框中突出显示该值。无论给定行上存在多少个实例,它都需要工作。到目前为止,我已经使用以下代码来确定一行中是否存在一个值,但是当存在多个相同值的实例时无法使突出显示正常工作。

strVal = "Find Me"
arrLines =Split(myTextbox.value, vbCrLf)
For Each strLine In arrLines
     If InStr(strVal, myTextbox.text) > 0 Then
          myTextbox.SelStart = InStr(strVal, my textbox.value)
           myTextbox.SelLength = Len(strVal)
           Exit For
    End if
 Next

我想让这个宏链接到一个按钮,并让宏在每次单击按钮时查找并突出显示下一个实例,无论该实例是在同一行还是在新行上。基本上,文本框的 Ctrl+F 功能。谢谢!

您可以试试这段代码(请参阅注释以获取解释):

Option Explicit

Private Sub CommandButton1_Click()
    Static lastInstancePosition As Long ' use Static variable to have its value persist after Sub exiting
    Dim instancePosition As Long

    strVal = "Find me"
    With myTextbox
        instancePosition = InStr(lastInstancePosition + 1, .Text, strVal) 'search string occurrence starting from last found item
        If instancePosition > 0 Then
            .SetFocus 'bring focus back ti the textbox after it has been taken by the button
            .SelStart = instancePosition - 1
            .SelLength = Len(strVal)
            lastInstancePosition = instancePosition ' update starting position for next search
       End If
    End With
End Sub