Search code examples
vbaexcelweb-scrapingie-automation

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


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


Solution

  • <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