在VBA功能结束时退出IE



我实现了几个依赖于从某些网站下载一些信息的功能。

这种函数的最简单示例是:

Public Function getSomething(webAddress As String)
Dim html As HTMLObjectElement
Set html = getWebContents(webAddress)
Set elems = html.body.getElementsByTagName(tagName)
...
End Function

从网站获取数据的功能是:

Public Function getWebContents(webAddress As String) As HTMLObjectElement
Dim ie As InternetExplorer
Dim html As HTMLDocument
Set ie = New InternetExplorer
ie.Visible = False
ie.Navigate webAddress
Do While ie.READYSTATE <> READYSTATE_COMPLETE
Application.StatusBar = "Trying ..."
DoEvents
Loop
Set getWebContents = ie.Document
'close down IE and reset status bar
'ie.Quit
Set ie = Nothing
Application.StatusBar = ""
End Function

问题是我似乎需要这条线,即。退出以取消注释以关闭 IE 实例。但是当我取消评论时,即。退出生产线

Set elems = html.body.getElementsByTagName(tagName)

生成错误。

似乎我无法使用函数getWebContent在IE退出时返回的HTMLObjectElement。如何处理?我可以实施一个尝试...最后在getSomething函数中阻止并在那里打开IE并在最后块中关闭。但是,我有许多类似性质的功能,并进行了许多类似的尝试......最后阻止似乎是一个愚蠢的想法。

有什么想法吗? 谢谢!

您应该定义一个过程来处理从创建到销毁的对象生存期。然后,可以将对象的引用传递给函数。

最后,即使任何支柱发生错误,您也可以释放对象。

Public Sub Main()
On Error GoTo ErrProc
Dim ie As InternetExplorer
Set ie = New InternetExplorer
'....
Dim obj As Object
obj = getWebContents(ie, "url")
Leave:
ie.Quit
Set ie = Nothing
Set obj = Nothing
Application.StatusBar = ""
On Error GoTo 0
Exit Sub
ErrProc:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub

Public Function getWebContents(ie As InternetExplorer, webAddress As String) As HTMLObjectElement
'...
End Function

你在 html 变量中保留了一个指向 DOM 的指针。如果您关闭IE,则指向不存在的内容。 简单的答案是在getSomething结束时关闭IE。在您的情况下,这意味着您必须重组代码,以便可以从getWebContent以外的其他地方访问IE变量

最新更新