2017-07-19 65 views
1

年底退出IE我实现了多种功能依赖于从下载一些网站的一些信息。在VBA函数

这样的功能的最简单的例子是:

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.Quit要取消注释以关闭IE实例。但是,当我取消注释ie.Quit行

Set elems = html.body.getElementsByTagName(tagName) 

生成错误。

看来,我不能用HTMLObjectElement通过函数返回getWebContents当IE已经辞去。如何处理?我可以实现一个try ... finally块在getSomething函数中,并打开ie,并在finally块中关闭。然而,我有许多类似的功能,并做出许多类似的尝试......终于块似乎是一个愚蠢的想法。

有什么想法? 谢谢!

回答

1

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

最后,你甚至可以如果在任何STANGE发生错误处理的对象。

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 
+0

好的,这是否意味着我需要在每个函数中初始化(和退出)getSomething我在Excel表中使用? – Gandalf

+0

是的,但在上面的例子中,为了使函数正常工作,IE对象必须保留在内存中,因此您无法控制'ie.Quit'。 –

+0

谢谢!看来VBA并不是一个非常灵活的工具。 – Gandalf

1

你保持一个指针在html变量的DOM。如果你关闭IE,你指向的东西不存在。 简单的答案是在getSomething结束时关闭IE。在你的情况,这意味着你必须调整你的代码,使你的IE变量是从其他地方比getWebContents