Search and Replace
Level: Intermediate
Search And Replace
automation - Internet Explorer & Web Browser
Control
Well, sometimes we need to search, or search and replace what is seeing in a HTML page.
There is no simple way to do this since HTML page is what it is: A final version of a "non" editable document.
Let's do our first approach: Find
If you didn't read before, to access the document inside IE or Web Brower control, the page has to be fully downloaded.
So, to set our HTMLDocument
object to the document loaded, we have to set it in DocumentComplete event of IE/WB control:
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
Set IEDoc = IE.document
End If
End Sub
After this, IEDoc
object allow us to access the properties and methods of the document (We will need this object later ;).
If you commonly do a search on a web page, surely you saw the menu Edit->Search on this page...(Ctrl+F).
This could be emulate with code but to this moment, it is not available according to MSDN.
If you prefer something standard, you cold use SendKeys
function from within VB:AppActivate IEDoc.Title & " - Microsoft Internet Explorer", True
SendKeys "%eb" 'Replace with valid combination ;)
But if you prefer a more custom solution, you could use this:
Private Sub Command1_Click()
With iedoc
Dim TxtRng As IHTMLTxtRange
Set TxtRng = .body.createTextRange
if TxtRng.findText("Comment") = True Then
TxtRng.Select
Else
MsgBox "Text not found", vbInformation, App.EXEName
End if
End With
End Sub
That code will search for the text "Comment" and if it is found, select it, if not, shows a message box saying so.
You could pass the string to search as parameter of a given Search function or you could create a form to enter the text to search. That's up to you!
If you decide to use the last, better add two text boxes and two command buttons given the Search AND replace capability.
The form Should look like this:
And the code behind those Command buttons should looks like:Private Sub Command1_Click(Index As Integer)
Dim TxtRng As IHTMLTxtRange
With IEDoc
Select Case Index
Case 0
Set TxtRng = .body.createTextRange
If TxtRng.findText(Text1(0).Text) = True Then
TxtRng.Select
Else
MsgBox "Text not found", vbInformation, App.EXEName
End If
Case 1
Dim sel As IHTMLTxtRange
Set TxtRng = .body.createTextRange
Do While TxtRng.findText(Text1(0).Text) = True
TxtRng.Select
Set sel = IEDoc.selection.createRange
sel.Text = Text1(1).Text
' You could paste valid HTML tags too!!
'sel.pasteHTML "<font color=red>" & Text1(1).Text & "</font>"
Loop
End Select
End With
End Sub
You could change the buttons to 3 choices:
Find, Replace and Replace all, you decide.
Hope you have enjoyed that work as i did.
;)
©2001 - Richie Simonetti