How to select all contents of a web page
and copy selected text to clipboard
Select
all contents of active web page - Internet Explorer Object
As
always, we will manage DocumentComplete
event: ' This code assumes that you already have declared
' a variable of type Internet Explorer called IE.
Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
With IE
.ExecWB OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT
.ExecWB OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT
End With
End If
End Sub
With previous code you have selected entire contents of web page and
put it in clipboard, ready to paste wherever you want.
How about
copying only selected text?
Well, we need some more objects variables
to get it: ' In general declaration section of main form
Dim WithEvents IE As InternetExplorer
Dim WithEvents HDoc As HTMLDocument 'We need to know when user does something with his mouse.
Dim TxtRng As IHTMLTxtRange ' To manage selected text.
As
always, we got handle to document object in DocumentComplete
event. Private Sub IE_DocumentComplete(ByVal pDisp As Object, URL As Variant)
If (pDisp Is IE) Then
Set HDoc = IE.document
End If
End Sub
To select text, user has to use the mouse. So, we will trap
only one event to set our TextRange.
These are (in order) the actions
that takes place when user selects text from web page:
- Mouse Down
- Mouse Drag
- Mouse Up
We will trap the last one since there is when
selection finish: Private Sub HDoc_onmouseup()
' We create a TextRange based upon user's selection
Set TxtRng = HDoc.selection.createRange
' We can change text selected if we want...
'TxtRng.Text = "It works!"
' ...or copy it to clipboard
IE.ExecWB OLECMDID_COPY, OLECMDEXECOPT_DONTPROMPTUSER
End Sub
related: Search and replace
Hope you have enjoyed that work as i did.
;)
©2001 - Richie Simonetti