Home » excel » vba – Simulate Click event on a DIV element

vba – Simulate Click event on a DIV element

Posted by: admin April 23, 2020 Leave a comment

Questions:

I cannot simulate a click event on a div element. The HTML code is this one:

<div id="export" data-export="true" data-timespan="">
    <button class="btn btn-default ladda-button" type="button" data-style="expand-right" data-spinner-color="#8899a6">
      <span class="Icon Icon--featherDownload"></span>
      <span class="ladda-label">
        Exportar datos
      </span>
    <span class="ladda-spinner"></span></button>
  <div class="hidden error server Callout Callout--danger">
    <p>Ocurrió un problema al exportar tus datos, inténtalo de nuevo más tarde.</p>
  </div>
</div>

In the webpage, is just a button that downloads a file when clicked. There is no URL. But after checking the code, is the div element what triggers the click event. Look the image.

Click to see image

That “g.handle” triggers a js.file form the website.

My vba code works perfect for doing other stuff in the website, but I cannot accomplish this task.

I’ve tried all this options:

Set div = HTMLDoc.getElementById("export")
div.FireEvent ("onclick")
div.Click


HTMLDoc.all.Item
Call HTMLDoc.parentWindow.execScript("g.handle", "JavaScript")

Nothing works. I’m kind of blocked right now and I have no idea of how to proceed. Maybe this has no solution? I have almost no idea of HTML and I have 0 idea of Javascript. But it must have a solution, because if I do it manually, i click on that DIV, wait some seconds and download my file.

Thanks in advance. Any help is welcome.

How to&Answers:

You didn’t specify if the highlighted portion was the html code for the button or not, but it appears from looking at it that it isn’t.

You can grab the class name for your button. The name may or may not be unique, and it’s difficult to know that without seeing the entire html code, but you can set the btn variable below to the first instance of that class name. If there are multiple class names in your html code, then you will need to use a For Each...Next statement to iterate through them (unless you know the instance number off hand).

So we will go with the first instance of your class, hence the reason for the (0) appended on the end.

Sub Test()

    Dim ie As New InternetExplorer, HTMLDoc As HTMLDocument, btn As Object
    ie.navigate Url 'whatever this may be

    ' Some code to wait for your page to fully load

    Set HTMLDoc = ie.document
    Set btn = HTMLDoc.getElementsByClassName("btn btn-default ladda-button")(0)
    btn.Click

End Sub