How to download a pdf file from browser using Excel VBA

前端 未结 1 1246
再見小時候
再見小時候 2020-12-18 12:12

I am using the below code snippet to download a PDF file from a website.

Option Explicit

Private Declare Function URLDownloadToFile Lib \"urlmon\" Alias   \         


        
相关标签:
1条回答
  • 2020-12-18 12:48

    I can think of a couple ways to do this. If you want to loop through a bunch of links, and download all files, you can setup an inventory list in Excel, like you see in the image below.

    Then, run the following Macro.

    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("Sheet1").Range("A2").Value
        buf = Split(URL, ".")
        ext = buf(UBound(buf))
        strSavePath = "C:\Users\rshuell\Desktop\Downloads\" & "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
    

    Now, if you just want to download one single file, run the script below.

    Sub DownloadFileWithVBA()
    
    Dim myURL As String
    'Right-click on the link named 'Sample Address File'
    'Click 'Copy Link Location'
    'Paste the link below
    myURL = "http://databases.about.com/library/samples/address.xls"
    
    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", myURL, False
    WinHttpReq.Send
    
    myURL = WinHttpReq.ResponseBody
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.ResponseBody
        oStream.SaveToFile ("C:\Users\Excel\Desktop\address.xls")
        oStream.Close
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题