VBA webbrowser findtext next occurrences

52 views Asked by At

I use a web browser control as a html editor in a MS Access 2010 database. I am trying to create a find text function to find certain strings and then select them.

I am using this code which works fine:

Private WithEvents oWeb As WebBrowser

Public Function FindAndHighlight(strText As String)
    Dim tr As IHTMLTxtRange
    
    Set oWeb = Me.webbrowser0.Object

    Set tr = oWeb.document.body.createTextRange
 
    tr.findText strText
    tr.Select
    tr.scrollIntoView
End Function

But this only finds the first occurrence of the search string. How do I - after I found the first occurrence - find the next one and then the next and so forth...?

Hope someone can put me on the right track...

BR, Emphyrio

1

There are 1 answers

0
emphyrio On BEST ANSWER

Eventually I found the answer myself. The solution was quite simple actually, looking in retrospect. Once I realized that the selection of the found keyword was also a text range, things fell into place. Here is my solution:

Private Function findAndHighlight(strText As String) As Boolean

Dim tr As IHTMLTxtRange, result As Long, MBtxt As String

If oWeb Is Nothing Then Set oWeb = Me.w1.Object

repeatSearch:

'create a text range from the selection
Set tr = oWeb.document.Selection.createRange

'if there is no selection, set the text range to the complete document
'if there is a selection:
'1. move the end point of the selection to the end of the document
'2. move the start point of the selection one character up (to prevent the finding the same word )
If Len(tr.Text) = 0 Then
    Set tr = oWeb.document.body.createTextRange
Else
    tr.setEndPoint "EndToEnd", tr
    tr.moveStart "character", 1
End If
   
'try to find the keyword in the text range
result = tr.findText(strText)

'if succesful: select the keyword and scroll into view
'if not succesful: clear the selection and prompt the user to start searching from the beginning
If result Then
    tr.Select
    tr.scrollIntoView
Else
    oWeb.document.Selection.empty
    MBtxt = "Your search string was not found, do want to search from the beginning of the document?"
    If MsgBox(MBtxt, vbYesNo, "keyword not found") = vbYes Then GoTo repeatSearch
End If

End Function