Excel VBA - 访问网站,生成报告并在 IE 对话框栏上按保存

Posted

技术标签:

【中文标题】Excel VBA - 访问网站,生成报告并在 IE 对话框栏上按保存【英文标题】:Excel VBA - Access Website, generate report & press save on IE dialog bar 【发布时间】:2020-04-23 11:20:35 【问题描述】:

我有一个关于某个主题的问题,该主题已在其他一些线程和论坛中讨论过,但我无法让它对我有用。所以我来这里问关于我个人代码的问题。

基本上,我访问一个 Intranet 站点并根据一些输入(通过复选框)使用来自 SAP 的数据创建一个报告。

我的问题是在生成报告后出现的,IE 提示我按下其对话框上的“保存”按钮。我无法使这部分自动化。

你能帮我吗?我想将报告存储在“下载”文件夹中。

您会在下面找到我的代码。 由于合规原因,我无法显示原始 URL。

任何帮助都会受到广泛赞赏。

最好的 西蒙


Dim ie As InternetExplorer
Dim html As HTMLDocument
Dim i As Integer

Set ie = New InternetExplorerMedium
ie.Visible = True
ie.navigate "https://blablablablablabla"
Application.Wait (Now + TimeValue("00:00:03"))

Set html = ie.document

html.getElementById("ctl00_MainContent_RadCboRepFilter1_Arrow").Click
Application.Wait (Now + TimeValue("00:00:01"))

html.getElementsByClassName("rcbList")(0).Children(5).Click
Application.Wait (Now + TimeValue("00:00:01"))

html.getElementById("ctl00_MainContent_RadCboRepFilter2_Arrow").Click
Application.Wait (Now + TimeValue("00:00:01"))

html.getElementsByClassName("rcbList")(0).Children(0).Click
Application.Wait (Now + TimeValue("00:00:01"))

html.getElementById("ctl00_MainContent_RadCboListOppStatus_ctl01").Click

html.getElementById("ctl00_MainContent_RadCboListOppStatus_ctl02").Click

html.getElementById("ctl00_MainContent_RadcboListSalesStage_ctl00").Click

html.getElementById("ctl00_MainContent_RadcboListSalesStage_ctl01").Click

html.getElementById("ctl00_MainContent_RadcboListSalesStage_ctl02").Click
Application.Wait (Now + TimeValue("00:00:01"))

html.getElementById("MainContent_BtnRunReport").Click

End Sub

【问题讨论】:

根据我的经验,当我们点击下载按钮时,IE浏览器会显示下载提示,让我们点击保存按钮下载文件。您确定 IE 浏览器允许您单击“另存为”按钮,而不是“保存”按钮。请检查您的网站代码,确保您设置了下载文件名。如果您能贴出如何生成报告和下载文件的相关代码,我们可能会更容易帮助您解决问题。 【参考方案1】:

一般情况下,当从 IE 浏览器下载文件时,它会显示一个提示让用户点击保存按钮。 我们可以使用 Application.SendKeys "%s" 命令单击 VBA 中的保存按钮。

示例代码如下:

Sub Test()
    Dim IE 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

HTML页面资源:

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

[注意]请检查您的IE浏览器设置,确保下载路径为“下载”文件夹。

【讨论】:

以上是关于Excel VBA - 访问网站,生成报告并在 IE 对话框栏上按保存的主要内容,如果未能解决你的问题,请参考以下文章

VBA - 从 Access (QueryTable) 生成 Excel 文件

生成 PDF 报告的 VBA 代码

使用 vba 在访问查询中传递参数值

将特定页码分配给 vba 中的 ms 访问报告

使用 excel vba 计算每行中的重复值和报告重复数

在访问 vba 的 excel 文件中未启用显示警报