Home » excel » excel – Referencing 'onclick' event for If statement – IE automation

excel – Referencing 'onclick' event for If statement – IE automation

Posted by: admin May 14, 2020 Leave a comment

Questions:

Apologies if this is a bit confusing. However, I am a little out of my depth here. I have a macro which is automating IE. At one point my macro navigates to a URL that is used to download a report. The URL is almost always the same. However, one digit within the link can sometimes change. The digit in the link that changes can only be 1 or 2. The onclick event of the button to get the report gives an indication which report will be generated. As a result, I need my macro to have an IF statement to read the onclick and if the onclick has 1, then it will navigate to the link with a 1 or if it is a 2, it will navigate to the link with a 2. I have provided the onclick details below:

Link with 'ReporttypeID=1'

<input name="btnContinue" class="primary" id="btnContinue" onclick="javascript:pop('Splash.aspx?SplashID=3&amp;../Reports/ReportView.aspx&amp;ReporttypeID=1&amp;lang=EN&amp;ruletypeid=5&amp;ruleid=0'); return false;" type="submit" value="Continue">```

Link with 'ReporttypeID=2'

<input name="btnContinue" class="primary" id="btnContinue" onclick="javascript:pop('Splash.aspx?SplashID=3&amp;../Reports/ReportView.aspx&amp;ReporttypeID=2&amp;lang=EN&amp;ruletypeid=5&amp;ruleid=0'); return false;" type="submit" value="Continue">```

My code is below, how do I call/reference the onclick id?

Sub login()
    Application.DisplayAlerts = False
    Dim url As String
    url = UserForm.Path2.Value

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    With ie 'Open IE
        .navigate url
        ieBusy ie
        .Visible = False

        ie.navigate "https://mylink.com/ReporttypeID=1" 'Currently navigate to this set link
    'Need IF statement to say if onclick = 1 then go to above link, else if it = 2 then go to the below link
        'ie.navigate "https://mylink.com/ReporttypeID=2"

        ieBusy ie

    End With 'End IE actions

    Application.DisplayAlerts = True
End Sub
How to&Answers:

These answers are based on there being one or the other always present.

Extract the onclick attribute and test whether it contains the string "ReporttypeID=1"

If Instr(ie.document.getElementById("btnContinue").getAttribute("onclick"),"ReporttypeID=1")> 0 Then
    'report 1
Else
  'report 2
End If

An alternative is to use a css attribute = value selector with contains operator to check nodeList length

If ie.document.querySelectorAll("[onclick*='ReporttypeID=1']").Length > 0 Then
    'report 1
Else
  'report 2
End If