首页 > 解决方案 > 如何在 64 位计算机上以 VBA 自动从 Internet Explorer 11 保存文件

问题描述

在此位置有一个 Excel 文件:https ://ufr.osd.state.ma.us/DM/GetDoc.aspx?DocId=165350&Library=EFILEDMProd

您可以看到顶部有一个名为“下载”的超链接。需要通过 Internet Explorer 11 在 64 位计算机上使用 Excel 中的 VBA 自动保存此文件。理想情况下,我还想将文件保存在特定路径和特定文件名(在本例中为“2018-042389332.xls”)。麻烦的是我找不到直接下载文件的方法,所以我不得不处理难以交互的文件保存对话框。到目前为止,我已经尝试过使用 SendKeys 的结果不一致。

这是我正在使用的代码的相关部分。到目前为止,单击“下载”按钮,在底部拉出“文件保存”对话框,在某些情况下,可以将文件保存为默认文件名。

    IE.Document.getElementById("LinkButton2").Click
    SendKeys "{F6}", True
    SendKeys "{TAB}", True
    SendKeys "{DOWN}", True
    SendKeys "{DOWN}", True
    SendKeys "{ENTER}", True

    SendKeys "{TAB}", True
    SendKeys "{TAB}", True
    SendKeys "{TAB}", True
    SendKeys "{ENTER}", True

标签: htmlexcelvbainternet-explorer

解决方案


为了获得更一致的结果,我会尝试在每个发送密钥后等待一秒钟,尝试在每个发送密钥之后插入:

Application.Wait (Now + TimeValue("0:00:01"))

您需要使用 Internet Explorer 吗?如果您有直接下载链接,这将更容易

Dim HttpReq As Object, myURL As String
Set HttpReq = CreateObject("Microsoft.XMLHTTP")
    myURL = *direct download link*
    HttpReq.Open "GET", myURL, False, "", ""
    HttpReq.send
    myURL = HttpReq.responseBody
    If HttpReq.Status = 200 Then
        Set oStrm = CreateObject("ADODB.Stream")
        oStrm.Open
        oStrm.Type = 1
        oStrm.Write HttpReq.responseBody
        oStrm.SaveToFile *File Path with file name and extension*,1 ' 1 = no overwrite, 2 = overwrite
        oStrm.Close
    End If

推荐阅读