VBA对象所需的错误尝试获取InnerText

我正在尝试创build一个代码,该代码将进入一个网站,input数据,提交,然后将答案返回给Excel中的单元格。 当我通过它,它工作正常,但是当我只是试图运行它,我得到运行时错误424; 所需对象。

我试图寻找一个很好的答案,但我只是没有把握如何解决这个问题。 我的问题在哪里? 我该如何纠正?

Sub Distance() Dim IE As Object ' Create InternetExplorer Object Set IE = CreateObject("InternetExplorer.Application") ' Make visible IE.Visible = True ' Go to site IE.Navigate "http://www.distance-cities.com/" ' Wait while IE loading... Do Until IE.READYSTATE = 4 DoEvents Loop IE.Document.getelementbyId("from").Value = "Stillwater, OK" IE.Document.getelementbyId("to").Value = "Hollis, OK" IE.Document.forms(0).submit Do Until IE.READYSTATE = 4 DoEvents Loop '*Below is where I get my error Sheet1.Range("E5").Value = IE.Document.getelementbyId("routemi").InnerText IE.Quit End Sub 

我很抱歉,如果这有点混乱。

感谢您的帮助!

像这样(未经testing):

 Dim el as object '... Set el = WaitForElement(IE.Document, "routemi", 1) If Not el is Nothing Then Sheet1.Range("E5").Value = el.innerText Else Msgbox "Element 'routemi' not found!" Exit Sub End if 

实用程序函数通过id获取元素,等待它出现:

 Function WaitForElement(doc As Object, id As String, maxWaitSec As Double) As Object Dim rv As Object, t t = Timer Do Set rv = doc.getElementById(id) DoEvents Loop While rv Is Nothing And (Timer - t) < maxWaitSec Set WaitForElement = rv End Function