【问题标题】:Downloading a file using Internet explorer 11 automatically using vba使用 vba 自动使用 Internet Explorer 11 下载文件
【发布时间】:2020-02-03 12:07:59
【问题描述】:

我正在尝试使用 InternetExplorer.Application 下载文件,但它总是打开一个窗口,要求保存或打开文件。有没有办法绕过这个并让它在后台运行和保存?这是我尝试过的一段代码。

Set ie = CreateObject("InternetExplorer.Application")
ie.Navigate "https://pastebin.com/raw/terAweb"
State = 0
Do Until State = 4
DoEvents
State = ie.readyState
Loop
Dim file: file= ie.Document.Body.innerHTML

【问题讨论】:

    标签: vba automation internet-explorer-11


    【解决方案1】:

    使用 URL Monikers API 而不是尝试与 InternetExplorer 应用程序 进行通信可能更简单。 这是专门为 Pastebin 做的吗?因为据我所知,它并不能真正使用它。但我想你可以用另一个?

    Option Explicit
    
    Private Declare PtrSafe Function URLDownloadToFileA Lib "URLMON" _
     (ByVal pcaller As Long, _
      ByVal szurl As String, _
      ByVal szFileName As String, _
      ByVal dwReserved As Long, _
      ByVal lpfnCB As Long) As LongPtr
    
    Sub Example()
    Dim Download$
    
        On Error GoTo ErrorHandler
    
        Download = URLDownloadToFileA(0, "myURL", "C:\Users\Name\Downloads\test.txt", 0, 0)
    
        Exit Sub
    
    ErrorHandler:
    
        MsgBox Err.Number & " " & Err.Description
    
    End Sub
    

    【讨论】:

    • 您好 GoldMachine,感谢您抽出宝贵的时间来写信。我知道 URLMonikers API,但如果可能的话,我正在寻找在 Internet Explorer 中工作的解决方案。
    【解决方案2】:

    请参考以下示例代码,使用getElementbyId方法找到下载按钮后,会显示下载提示,我们可以使用Application.SendKeys "%{s}"命令点击保存按钮。

    Sub downloadfile()
    
            Dim IE As Object, Data As Object
            Dim ticket As String
    
            Set IE = CreateObject("InternetExplorer.Application")
    
            With IE
                .Visible = True
                .navigate ("https://dillion132.github.io/default.html")
    
                While IE.ReadyState <> 4
                    DoEvents
                Wend
    
                'Trigger the download 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.
            'loadingSite
            End With
            Set IE = Nothing
        End Sub
    

    网页内容:

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

    【讨论】:

    • 你好吕志,这段代码出错了。你试过运行它吗?
    • 是的,它在我这边工作得很好,你能告诉我错误信息吗?尝试设置调试器检查您的代码并找出哪一行抛出此错误消息?
    • 编译错误。 Application.wait 和 .sendkeys 给出,方法或数据成员未找到。
    • 请检查您是否已经在 Access for Excel 的对象库中添加了引用(如果没有,请打开 VB 编辑器,然后打开工具 > 引用 > 在列表中向下滚动到 Microsoft Excel 16.0 对象库(或类似的东西)>勾选它>确定)。这是similar thread,你可以参考一下。
    • 代码没有按预期工作,我用不同的方法解决了这个问题。
    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 2016-12-23
    • 2013-07-26
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    相关资源
    最近更新 更多