我正在使用excel 2010,vba。我有一个工作的网页 - 我创建的,当用户点击链接时,我想拦截该链接,并运行vba(而不是javascript onclick事件)。即,如果可能,将onclick事件绑定到VBA函数或sub。有些网站暗示可以做到。自动化大师的问题。注意我不想点击通过自动化的链接(以下代码执行此操作)我希望用户单击并且VBA拦截点击(注意,我不想用更多js替换javascript我想要致电VBA)。我正在使用InternetExplorer对象,但可能需要使用另一个对象或库引用。
以下代码(示例)打开了www的第一个网页,然后点击了该链接。我想拦截这个点击并运行vb代码。
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
答案 0 :(得分:1)
您可以使用类模块和WithEvents
来连接可以从IE触发的VBA托管事件。此代码用于链接,但也可以捕获大多数其他事件。
编辑:添加鼠标悬停/出来以获得良好的衡量标准......
常规模块
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(课程模块)
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
将项目引用添加到: