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

时间:2015-04-22 17:39:28

标签: excel vba excel-vba

我正在尝试创建一个代码,该代码将转到网站,放入数据,提交,然后将答案返回到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

如果这有点乱,我道歉。

谢谢你的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您需要在每个点(在.Navigate2.Click之后)进行适当的等待,以允许页面加载。由于现代浏览器针对CSS进行了优化,因此我使用CSS选择器定位ID。另外,我将页面导航的方法更新为.Navigate2

Option Explicit
Public Sub Distance()
    Dim ie As New InternetExplorer
    With ie
        .Visible = True

            .Navigate2 "http://www.distance-cities.com/"

            While .Busy Or .readyState < 4: DoEvents: Wend

            With .document
                .querySelector("#from").Value = "Stillwater, OK"
                .querySelector("#to").Value = "Hollis, OK"
                .querySelector("[type=submit]").Click
            End With

           While .Busy Or .readyState < 4: DoEvents: Wend
           Debug.Print .document.querySelector("#routemi").innerText
        .Quit
    End With
End Sub