让Excel等待IE加载 - 间歇424对象所需的错误

时间:2018-01-25 15:12:03

标签: vba web-scraping

我的代码将内部网站抓取到我们公司的数据表。它会多次访问网站,具体取决于用户需要返回的帐户数量。我们间歇地得到一个

  

424对象需要

在从网站获取数据的函数中。我认为当我们内联网上的负载较高时,它会减慢系统速度,从而导致此错误。

我想确保在尝试从数据表中获取信息之前加载网页。这就是我今天的代码所在:

' IE Version 8+
Set objIE = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}") 
DoEvents

With objIE
    .Visible = False
    .Navigate "internalsite.aspx"        

    While .Busy = True Or .Readystate <> 4: DoEvents: Wend
    While .Document.Readystate <> "complete": DoEvents: Wend

    .Document.getElementById("Region_txtAccount").Value = sAccountNum

    While .Busy = True Or .Readystate <> 4: DoEvents: Wend
    While .Document.Readystate <> "complete": DoEvents: Wend

    .Document.getElementById("Region_bRunInfo").Click

    While .Busy = True Or .Readystate <> 4: DoEvents: Wend
    While .Document.Readystate <> "complete": DoEvents: Wend

End With

thisCol = 53
thisColCustInfo = 53

GetOneTable objIE.Document, 9, thisCol

'Cleanup:
    objIE.Quit
    Set objIE = Nothing

GetWebTable_Error:
    Select Case Err.Number
        Case 0
        Case Else
        Debug.Print Err.Number, Err.Description
        Stop
    End Select

我相信这个thread拥有解决方案。我只需要一点点洞察力就可以将它应用到我的代码中。

1 个答案:

答案 0 :(得分:1)

Internet Explorer .Busy.readyState的一个不幸的问题是,某些网页不是100%可靠。

您可以用来修复问题的 hack 只是等待您的对象变为可用。您的对象将是引发错误的对象。

Sub ieBusy(ie As Object)

    Do While ie.busy Or ie.readystate < 4
        DoEvents
    Loop

End Sub

Sub Test()

    Dim objIE As Object

    Set objIE = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}") ' IE Version 8+
    DoEvents

    With objIE
        .Visible = False
        .Navigate "internalsite.aspx"

        ieBusy objIE

        ' this is your hack:
        On Error Resume Next
        Do While .Document.getElementById("Region_txtAccount") Is Nothing
            DoEvents
        Loop
        On Error GoTo 0
        .Document.getElementById("Region_txtAccount").Value = sAccountNum

        ieBusy objIE

        ' this is your hack:
        On Error Resume Next
        Do While .Document.getElementById("Region_bRunInfo") Is Nothing
            DoEvents
        Loop
        On Error GoTo 0
        .Document.getElementById("Region_bRunInfo").Click

        ieBusy objIE

    End With

        thisCol = 53
        thisColCustInfo = 53

    GetOneTable objIE.Document, 9, thisCol

    'Cleanup:
    objIE.Quit
    Set objIE = Nothing

GetWebTable_Error:
Select Case Err.Number
    Case 0
    Case Else
    Debug.Print Err.Number, Err.Description
        Stop
End Select

End Sub