2015-04-22 54 views
1

我想创建一个代码,将去到一个网站,放入数据,提交它,然后将答案返回到Excel中的单元格。当我通过它时,它工作正常,但是当我试图运行它时,我得到运行时错误424;所需对象。VBA对象所需的错误试图获取InnerText

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

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 

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

感谢您的帮助!

+0

如果它工作在调试的时候,但直通运行时出现故障,可能是计时问题,您的网页未完全加载,或者您尝试访问的元素尚未添加到网页的内容中。尝试添加一个简短的“等待”,然后尝试访问相关元素。 –

+0

嗨,我添加了Application.Wait(现在+ TimeValue(“0:00:10”)),这有诀窍,有没有更好的方法来做到这一点? – TheLeastofThese

+0

您可以将'getelementbyid()'封装在一个循环中,直到返回值不是'Nothing'(但是您还应该添加一个时间限制,准备等待多长时间,以便您可以跳出循环元素从不出现......) –

回答

1

像这样(未经):

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 
+0

我正在努力实现这个目标,我在哪里应用这个?对于简单的问题抱歉! – TheLeastofThese

+0

用我的示例代码的第一个块代替代码的最后一行的第三行,并将函数包含在模块中。 –

+0

谢谢,我在'Set rv = doc.getElementById(id)' – TheLeastofThese