【问题标题】:Quitting the IE in the end of VBA function在 VBA 函数结束时退出 IE
【发布时间】:2017-07-19 10:18:50
【问题描述】:

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

此类函数的最简单示例是:

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 the line

Set elems = html.body.getElementsByTagName(tagName)

产生错误。

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

有什么想法吗? 谢谢!

【问题讨论】:

    标签: windows vba internet-explorer


    【解决方案1】:

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

    最后,即使发生任何错误,您也可以处置该对象。

    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
    

    【讨论】:

    • 好的,这是否意味着我需要在我在 Excel 表中使用的每个函数 getSomething 中初始化(并退出)IE?
    • 是的,但是在您上面的示例中,为了使该功能正常工作,IE 对象必须保留在内存中,因此您无法控制 ie.Quit
    • 谢谢! VBA 似乎不是一个非常灵活的工具。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 2020-04-28
      • 2016-07-29
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多