在IE10中下载文件

时间:2014-12-24 14:04:58

标签: vba excel-vba automation download internet-explorer-10

我正在开发一个Internet Explorer自动化项目。代码从网站下载并保存文件。它可以使用'SendKeys'下载和保存文件,但它不是一个可靠的方法,因为我无法检测到下载通知:

The notification which is currently undedectable

有没有办法在没有“SendKeys”的情况下下载和保存文件?或者至少有办法检测此通知的存在吗?

Ps - 我已经提到了这些链接,它们对IE8下载有帮助:

任何帮助?

1 个答案:

答案 0 :(得分:1)

为什么要使用SendKeys方法下载文件?对不起,这是错误的做法。 使用API​​!

解决方案1:

Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
  "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal _
    szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long


Sub DownloadFilefromWeb()
    Dim strSavePath As String
    Dim URL As String, ext As String
    Dim buf, ret As Long
    URL = Worksheets("References & Resources").Range("URLMSL").Value
    buf = Split(URL, ".")
    ext = buf(UBound(buf))
    strSavePath = ThisWorkbook.Path & "\" & "DownloadedFile." & ext
    ret = URLDownloadToFile(0, URL, strSavePath, 0, 0)
    If ret = 0 Then
        MsgBox "Download has been succeed!"
    Else
        MsgBox "Error"
    End If
End Sub

来源:VBA - Save a file from a Website

解决方案2:

Option Explicit

Sub DownloadXLFileFromURL()

    Dim myURL As String, sFilename As String
    myURL = "http://img.chandoo.org/hw/max-change-problem.xlsx"
    sFilename = Environ("SystemDrive") & Environ("HomePath") & _
            Application.PathSeparator & "Desktop" & Application.PathSeparator & _
            "file.xlsx"

    Dim WinHttpReq As Object, oStream As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", myURL, False ', "username", "password"
   WinHttpReq.Send

    myURL = WinHttpReq.ResponseBody
    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.ResponseBody
        oStream.SaveToFile sFilename, 2  ' 1 = no overwrite, 2 = overwrite
       oStream.Close
    End If

End Sub

来源:Download file from URL using VBA

解决方案3:

最后,您可以创建自定义类,它可以创建MS IE的实例。现在,您可以通过使用其属性和事件来控制/管理IE对象,例如DownloadBeginDownloadCompleteFileDownload

请参阅:Using the WebBrowser Control from Visual Basic

注意:从未尝试过之前......