简体   繁体   中英

Excel VBA click JavaScript button

Can someone show me the VBA code to click the "Copy to Clipboard" button on this webpage? The button has an element id="ToolTables_example_0", but I cannot figure out how to execute the script from Excel. I have tried re-engineering many different VBA codes I found, but no luck. Seems like it should be so simple! Thanks!

https://spotwx.com/products/grib_index.php?model=nam_awphys&lat=30.26678&lon=-97.76905&tz=America/Chicago&display=table

The following code requires that you add Microsoft HTML Object library and Microsoft Internet controls to your project with the VBE's Tools ► References command.

Here are two methods of clicking that button.

Sub clickIt()
    Dim a As Long, u As String, till As Double
    Dim el As MSHTML.IHTMLElement, ie As New SHDocVw.InternetExplorer

    u = "https://spotwx.com/products/grib_index.php?model=nam_awphys&lat=30.26678&lon=-97.76905&tz=America/Chicago&display=table"

    ie.Silent = True
    ie.Visible = True

    ie.navigate u
    Do While ie.Busy Or ie.readyState <> 4: DoEvents: Loop
    'wait an extra second or so (this usually isn't necessary but helped with this page)
    till = Timer + 1
    Do While Timer < till: DoEvents: Loop

    'Method 1: Loop through all the A elements looking for the right ID
    For a = 0 To ie.document.getElementsByTagName("a").Length - 1
        With ie.document.getElementsByTagName("a")(a)
            If .ID = "ToolTables_example_0" Then
                Debug.Print "found ToolTables_example_0 in a loop"
                .Click
                'the table data should be on the clipboard
                Exit For
            End If
        End With
    Next a

    'Method 2: Locate the right A element using its ID directly
    On Error Resume Next
    Set el = ie.document.getElementById("ToolTables_example_0")
    On Error GoTo 0

    If Not el Is Nothing Then
        Debug.Print "found ToolTables_example_0 directly"
        el.Click
        'the table data should be on the clipboard
    End If

    ie.Quit
    Set ie = Nothing

End Sub

I could not fully test that as my ie does not have the Adobe FlashPlayer installed (and I would prefer to keep it that way). If you can manually open Internet Explorer, navigate to that page, click the button and then paste the content that was copied to the clipboard back to your Excel worksheet then I see no reason why it should not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM