I'm using excel 2010, vba. I have a web page at work - which I created, and when the user clicks on a link, i want to intercept that link, and run vba (not the javascript onclick event). ie bind the onclick event to VBA function or sub if possible. Some sites hint it can be done. Question for an automation guru. Note i do not want to click the link thru automation (the below code does this) I want the user to click and the VBA intercept the click ( note, i don't want to replace the javascript with more js I want to call VBA). I'm using the InternetExplorer object but might need to use another ie object or library reference as you advise.
The below code (example) opens the www's first web page and clicks on the link. I want to intercept this click and run vb code.
Dim ie As InternetExplorer
Set ie = New InternetExplorer
sURL = "http://info.cern.ch/hypertext/WWW/TheProject.html" ' www's first web page
ie.Navigate sURL
ie.Visible = True
Do While ie.Busy
DoEvents
Loop
Set oForm = ie.Document.getElementsByName("0") ' worlds first ever anchor/ hyper link
Set oLink = oForm.Item(0)
'oLink.onclick = ' set/add to VBA function to replace/set javascript onlclick event ie. to intercept click
oForm.Item(0).Click ' run vba code to display msgbox "hello World" not navigate
You can use a class module and WithEvents
to hook up VBA-hosted events which can be triggered from IE. This code is for links, but most other events can also be captured.
EDIT: added mouseover/out for good measure...
Regular module
Private lnks As Collection 'of clsLink
Sub Tester()
Dim ie As InternetExplorer, el, sURL
Dim lnk As clsLink
Set ie = New InternetExplorer
sURL = "http://info.cern.ch/hypertext/WWW/TheProject.html"
ie.Navigate sURL
ie.Visible = True
Do While ie.Busy
DoEvents
Loop
Set lnks = New Collection
For Each el In ie.document.getElementsByTagName("a")
Set lnk = New clsLink
lnk.Init el
lnks.Add lnk
Next
End Sub
clsLink (class module)
Option Explicit
'note "WithEvents" declaration
Private WithEvents lnk As MSHTML.HTMLAnchorElement
Private Function lnk_onclick() As Boolean
Debug.Print "Link: '" & lnk.innerText & "' clicked!"
lnk_onclick = False 'cancels navigation
'lnk_onclick = True 'doesn't cancel navigation
End Function
Private Sub lnk_onmouseout()
With lnk.Style
.Color = "#00F"
.backgroundColor = "#FFF"
End With
End Sub
Private Sub lnk_onmouseover()
With lnk.Style
.Color = "#F00"
.backgroundColor = "#0F0"
End With
End Sub
Public Sub Init(el)
Set lnk = el
End Sub
Add project references to:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments