Matus Kovac
Matus Kovac

Reputation: 19

VBA to click web button with dynamic elementID and repetitive class

I am quite new to VBA/html, trying to automate filling a form, but cannot even call it ... I searched the web for weeks tried many different code combinations, but none got me there.

The HTML code/element looks like this:

div title:"TextText" class:"text-truncate mb-2" id="abc_sidebar_startmenuitem" data-type="record" data-appid="82" data url="index.cfm?Xxx=&Yyy=">

i class="fa icon-app-82 mr-1 fa-fw">/i>

span class="clickable" id="ext-eng123">Text/span>
/div>

Problem is that class="clickable" is 30th appearance of clickable on the page, id="ext-eng123" is built from the text ext-eng and 3 variable unknown digits, always different.

Example of VBA code used:

Sub GetClick()
    Dim ie As Object
    Set ie = CreateObject("internetexplorer.application")
    With ie
        .Visible = True
        .navigate "https://company.application.com/home/index.cfm?Tab=home"
        Do While .Busy
            DoEvents
        Loop
        Do While .readyState <> 4
            DoEvents
        Loop
    End With
    Dim objIE As Object
    objIE = document.getElementByClassName("clickable")(29)
    objIE.Click
End Sub

I tried over 10+ different code samples, including calling frame number, none worked, I am stuck.

Upvotes: 0

Views: 998

Answers (1)

SIM
SIM

Reputation: 22440

Try the following code. It is hard to give any solution without playing with that site. They are always hypothetical.

Sub GetClick()
    Dim IE As New InternetExplorer, Html As HTMLDocument

    With IE
        .Visible = True
        .Navigate "https://company.application.com/home/index.cfm?Tab=home"
        While .Busy = True Or .ReadyState < 4: DoEvents: Wend
        Set Html = .Document
    End With

    ''If the problem still persists, make sure to put here some delay

    Html.querySelector(".clickable[id^='ext-eng']").Click
End Sub

Another approach might be something like (if the word "Text" didn't appear anywhere with the same class name):

For Each elem In Html.getElementsByClassName("clickable")
    If InStr(elem.innerText, "Text") > 0 Then elem.Click: Exit For
Next elem

Reference to add:

Microsoft Internet Controls
Microsoft HTML Object Library

Upvotes: 2

Related Questions