VBA InternetExplorer页面加载错误

时间:2016-09-26 07:51:54

标签: excel excel-vba vba

当我使用F5运行下面的代码时,它会给我一个错误消息"对象变量或未设置块变量" (设置DivClasses = HTMLDoc.getElementsByClassName(" srp_containerfl")),因为点击按钮后页面未完全加载(Do While IEObj.readyState< > 4或IEObj.Busy:DoEvents:Loop)这行代码无法正常工作,因为它会在完全加载页面之前进入下一行。

如果我手动运行此代码并给它一些时间来加载页面,它运行正常。

Sub Fetch_NaukriDotCom_Data()

Dim IEObj                   As InternetExplorer
Dim HTMLDoc                 As MSHTML.HTMLDocument
Dim divcl                   As MSHTML.IHTMLElement
Dim DivClass                As MSHTML.IHTMLElement
Dim DivClasses              As MSHTML.IHTMLElementCollection
Dim DataContainer           As MSHTML.IHTMLElement
Dim DataContainerChild      As MSHTML.IHTMLElement
Dim DataContainerChilds     As MSHTML.IHTMLElementCollection
Dim DataOneContainer        As MSHTML.IHTMLElement
Dim DataOneContainers       As MSHTML.IHTMLElementCollection
Dim StrClassName            As String
Dim Int_i                   As Integer

Set IEObj = New InternetExplorer
IEObj.Visible = True
IEObj.navigate "https://www.naukri.com/"

With IEObj
    Do While .readyState <> 4 Or .Busy: DoEvents: Loop

    .document.getElementsByName("qp").Item.innerText = "VBA Developer"
    .document.getElementsByName("ql").Item.innerText = "Noida"
    .document.getElementById("qsbFormBtn").Click
End With

Do While IEObj.readyState <> 4 Or IEObj.Busy: DoEvents: Loop 'This loop is not working properly, as it is going
                                                             'to next line, without completely loading the page

Set HTMLDoc = New MSHTML.HTMLDocument
Set HTMLDoc = IEObj.document
Set DivClasses = HTMLDoc.getElementsByClassName("srp_container fl  ") 'Here Error occuring

Set DataContainerChilds = DivClasses.Item.Children

End Sub

请帮我解决这个问题。

由于 卡希夫

1 个答案:

答案 0 :(得分:0)

是的IE有时会表现得很有趣,因此我使用了这个

替换

Do While IEObj.readyState <> 4 Or IEObj.Busy: DoEvents: Loop

Do While IEObj.readyState <> 4 Or IEObj.Busy: Wait 5 : Loop

然后在代码末尾粘贴此过程。 Wait 5表示在再次检查状态之前等待5秒钟。

Private Sub Wait(ByVal nSec As Long)
    nSec = nSec + Timer
    While nSec > Timer
        DoEvents
    Wend
End Sub