我在 MS Access 2010 数据库中使用 Web 浏览器控件作为 html 编辑器。我正在尝试创建一个查找文本函数来查找某些字符串,然后选择它们。
我正在使用这段代码,效果很好:
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
但这只能找到搜索字符串的第一次出现。在找到第一个出现后,我如何找到下一个,然后找到下一个,依此类推......?
希望有人能让我走上正轨......
BR,艾菲里奥
最终我自己找到了答案。回想起来,解决方案实际上很简单。一旦我意识到找到的关键字的选择也是一个文本范围,事情就水到渠成了。这是我的解决方案:
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