Using VBA to click on a link/button in an IE web page

假装没事ソ 提交于 2019-12-24 02:57:23

问题


I have read a lot of information on using VBA to click on a link in IE, but I cannot get it to work in my case. The relevant HTML code is as follows:

<div id="LinkButton_3" widgetId="LinkButton_3">
    <a class="Row_Icon" data-dojo-attach-point="linkNode" data-dojo-attach-event="onClick:_onLinkButtonClicked">Company XYZ. - #12345</a>
</div>

The VBA code I have tried, with 3 different attempts noted, is as follows:

Dim ieApp           As SHDocVw.InternetExplorer
Dim ieDoc           As MSHTML.HTMLDocument
Dim button          As HTMLInputButtonElement
Dim div             As HTMLDivElement

' Create a new instance of IE
    Set ieApp = New InternetExplorer

' Uncomment this line for debugging purposes.
    ieApp.Visible = True
' Go to the page we're interested in.
    ieApp.Navigate "MyURL.com"


    Do While ieApp.Busy: DoEvents: Loop
    Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop

    Set ieDoc = ieApp.Document
' Try #1.
' Nothing happened on the web page after these 3 lines were executed.
        Set button = ieDoc.getElementById("LinkButton_3")
        button.Focus
        button.Click
' Try #2
' Nothing happens - button is not clicked.
        Set div = ieDoc.getElementById("LinkButton_3")
        div.FireEvent "onClick"
' Try #3
' Nothing happens - button is not clicked.
        div.Click

' Close the instance of IE.
        ieApp.Quit
' Clean up.
        Set ieApp = Nothing
        Set ieDoc = Nothing

Any thoughts on what I might be doing wrong or other suggestions would greatly be appreciated.

TMc


回答1:


<div id="LinkButton_3" widgetId="LinkButton_3">
    <a class="Row_Icon" data-dojo-attach-point="linkNode" data-dojo-attach-event="onClick:_onLinkButtonClicked">Company XYZ. - #12345</a>
</div>

What you want to click on is the anchor (a) tag, not the div. So, you can find the div with its id and then click on its one and only child with

button.Children(0).Click



回答2:


You can also use a CSS querySelector of #LinkButton_3 a. This is the a tag within the element with id LinkButton_3. The "#" means id. The " a" means a tag within.

.querySelector method belong to the HTMLDocument.

You can do:

ieDoc.querySelector("#LinkButton_3 a").Click


来源:https://stackoverflow.com/questions/41746918/using-vba-to-click-on-a-link-button-in-an-ie-web-page

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