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

时间:2018-02-07 04:24:47

标签: vba excel-vba textbox highlighting excel

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

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 功能。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码(请参阅解释说明):

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