在Excel VBA中处理InternetExplorer对象事件
我想在我的Excel VBA代码中处理对象InternetExplorer
的事件。
在此页面上,您可以看到InternetExplorer对象的所有可用事件: http : //msdn.microsoft.com/zh-cn/ie/aa752084(v=vs.94).aspx
Dim ie As InternetExplorer Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.Navigate "http://www.google.com" While ie.Busy DoEvents Wend Set mybrowser = Nothing
我想捕捉一个BeforeNavigate
和一个NavigateComplete
事件,上面的代码应该触发。
我将如何设置我的代码来做到这一点?
使用WithEvents
关键字Dim
。
从文档 :
句法
Dim [ WithEvents ] varname [([subscripts])] [As [New] type] [,[WithEvents] varname [([subscripts])] [As [New] type]]。 。 。
WithEvents :可选。 指定varname是用于响应由ActiveX对象触发的事件的对象variables的关键字。 WithEvents仅在类模块中有效 。 您可以使用WithEvents声明尽可能多的单个variables,但不能使用WithEvents创build数组。 WithEvents不能使用New。
Clmusy示例Class1
类模块,仅用于说明目的:
Option Explicit Dim WithEvents ie As InternetExplorer Private Sub Class_Initialize() Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.Navigate "http://www.duckduckgo.com" While ie.Busy DoEvents Wend Set ie = Nothing End Sub
用法示例:
Sub tester() Dim c As Class1 Set c = New Class1 End Sub