Excel VBA control IE

ⅰ亾dé卋堺 提交于 2021-02-19 07:54:05

问题


I have found the following code on the WiseOwl website. I am trying to find a working example (to learn from) on how to enter a seach string into Googles search field. I keep getting a debug error 462 andf cant get past this. The line causing the problem is:

  ieApp.Document.getElementById("gbqfqw").Value = "Excel VBA"

My total code is:

Sub FillInBBCSearchForm()

Dim ieApp As New SHDocVw.InternetExplorer

ieApp.Visible = True

'go to the website of interest

ieApp.Navigate "http://www.google.co.uk"

Do While ieApp.Busy

DoEvents

Loop

'wait for page to finish loading

Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE

DoEvents

Loop 

'fill in the search form

ieApp.Document.getElementById("gbqfqw").Value = "Excel"  'DEBUG ERROR HERE

'wait for page to finish loading

Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE

DoEvents

Loop


End Sub

Any help is appreciated.

Thanks


回答1:


Instead of referring to an element by its ID, I usually loop through all elements on the page, and find it by its name. It runs a bit slower, but gets the job done.

Try the following:

Sub FillInBBCSearchForm()

Dim ieApp As New SHDocVw.InternetExplorer

'go to the website of interest
ieApp.Navigate "http://www.google.co.uk"

'wait for page to finish loading
Do While ieApp.Busy: DoEvents: Loop
'it sometimes takes more than one wait loop for the page to load properly
Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop

'find the required field
Set doc = ieApp.Document.getElementsByTagName("input")
    For Each lnk In doc
        If lnk.Name = "q" Then
            'input search text
            lnk.Value = "Excel VBA"
        End If
    Next lnk

ieApp.Visible = True
AppActivate ieApp.Document.Title

End Sub


来源:https://stackoverflow.com/questions/31922038/excel-vba-control-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!