首页 > 解决方案 > 从网站下载 Excel 文件后如何在 IE11 中单击保存按钮

问题描述

我正在从特定网站下载 Excel 文件,但 IE11 促使我点击保存按钮,我希望它使用 VBA 自动执行。

我已经尝试过Application.SendKeys("%s")方法,但它没有奏效,因为我不是 VBA 专家,我无法更进一步。

Sub dailyreport()
    Dim IE As Object    
    Dim doc As HTMLDocument
    Dim Element As HTMLLinkElement

    Set IE = New InternetExplorer
    IE.Visible = True
    IE.navigate ("https://mywebsite.com")

    Do While IE.Busy
        Application.Wait DateAdd("S", 1, Now)
    Loop

    Set doc = IE.document
    doc.getElementById("login").Value = "username"
    doc.getElementById("password").Value = "password"
    doc.getElementById("loginButton").Click

    ' Navigate to report page Do While IE.Busy Application.Wait DateAdd ("S", 1, Now) Loop IE.navigate ("https://mywebsite.com/report") 'Since the hyperlink doesn' t have any link I 'm searching the link with href value (Export View)

    Do While IE.Busy
        Application.Wait DateAdd("S", 30, Now)
    Loop

    For Each Element In doc.Links
        If InStr(Element.innerText, "Export View") Then
            Call Element.Click
            Exit For
        End If
    Next Element
End Sub

单击导出视图超链接后,它开始下载,但最后 IE 要求我单击打开或保存按钮。

“你要保存还是打开”

所以我想使用 VBA 单击保存按钮。

标签: vbainternet-explorerweb-scrapingdownload

解决方案


请参考以下代码,在点击下载提示保存按钮之前,我们可以等待提示出现,然后使用Application.SendKeys "%{s}"命令点击保存按钮:

Sub Test()
    Dim IE As Object

    Dim startDateText As Object, endDateText As Object

    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Visible = True
        .Navigate "<the website url>"

        While IE.ReadyState <> 4
            DoEvents
        Wend

        'click the button to download the file.
        IE.Document.getElementbyId("btnDowloadReport").Click

        'wait the download prompt appear
        Application.Wait (Now + TimeValue("00:00:03"))

        Application.SendKeys "%{s}"

        'Waiting for the site to load.
    End With
    Set IE = Nothing
End Sub

网页内容:

<a id="btnDowloadReport" href="https://research.google.com/pubs/archive/44678.pdf" download>Download</a>

推荐阅读