Search code examples
vbaexceltextboxhighlighting

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


I am attempting to create a search inside of a multiline textbox that will find each instance of a value and highlight that value inside the textbox. It will need to work regardless of how many instances exist on a given line. So far I have used the following code to identify if a value exists on a line but cannot get the highlighting to work properly when there are multiple instances of the same value.

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

I want to have this macro linked to a button and have the macro find and highlight the next instance each time the button is clicked regardless if that instance is on the same line or a new line. Basically, a Ctrl+F feature for the textbox. Thanks!


Solution

  • You can give this code a try (see comments for explanations):

    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