代码在F8阶段工作,但不正常运行时
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
中断ie.document.getElementById("logo").Click
a a
'424'对象需要错误
因为这是对象尚不可用的问题,所以解决您的问题的最简单方法是首先将对象设置为对象 – 循环直到它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
即使在readyState = Complete
,在某些情况下,对象也没有完全初始化。 这可能部分是由于除了您看到的主HTML页面之外,还有多个iFrames可以完成自己的function。
我同意K.Davis,准备状态并不总是可靠的。 尝试这个:
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop Sleep(100) Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop