Sub InternetPractice()
Dim ie As InternetExplorer
Set ie = New InternetExplorer
ie.Visible = True
ie.navigate "https://www.yahoo.com"
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
ie.document.getElementById("uh-search-box").Value = "Earth"
ie.document.getElementById("uh-search-button").Click
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
ie.document.getElementById("logo").Click
Set ie = Nothing
End Sub
当我逐行逐步执行代码时,代码会正常工作,但在正常运行时则不行。我尝试在某些部分插入多达45秒的休息时间但没有成功。
正常运行,代码在ie.document.getElementById("logo").Click
期间中断并给我一个
&#39; 424&#39;对象必需的错误
答案 0 :(得分:2)
因为这是对象尚不可用的问题,所以最简单解决问题的方法是先将logo
设置为对象 - 循环直到它为{{1然后单击它。
Not Nothing
所以你基本上要替换这一行:
Option Explicit
Sub InternetPractice()
Dim ie As New InternetExplorer, logoBtn As Object
With ie
.Visible = True
.navigate "https://www.yahoo.com"
Do While .Busy Or .readyState <> 4: DoEvents: Loop
.document.getElementById("uh-search-box").Value = "Earth"
.document.getElementById("uh-search-button").Click
Do While .Busy = True Or .readyState <> 4: DoEvents: Loop
On Error Resume Next
Do While logoBtn Is Nothing
Set logoBtn = .document.getElementById("logo")
DoEvents
Loop
On Error Goto 0
End With
logoBtn.Click
End Sub
用这个:
ie.document.getElementById("logo").Click
即使在 Dim logoBtn As Object
Do While logoBtn Is Nothing
Set logoBtn = ie.document.getElementById("logo")
DoEvents
Loop
logoBtn.Click
之后,在某些情况下,对象也未完全初始化。这可能部分是因为除了您看到的主HTML页面之外,还有多个iFrame做了自己的事情。
答案 1 :(得分:1)
我同意K.Davis,Ready State并不总是可靠的。 试试这个:
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
Sleep(100)
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop