Search code examples
vbapdfurldownload

VBA to save PDF from URL to local folder


I'm trying to cycle through several url's to download the pdf to a local folder.

An example of the url is https://find-energy-certificate.service.gov.uk/energy-certificate/8309-9619-9729-7796-8423?print=true

This is the vb I've written so far.

Dim sveloc As String
Dim svenme As String
Dim url    As String

sveloc = Application.ActiveWorkbook.Path & "\Saved EPCs"

i = 7
Do Until sh01.Cells(i, 27) = "" 'all cells in the list are populated with no gaps

    url = sh01.Cells(i, 27)
    svenme = sh01.Cells(i, 2)
    sveloc = sveloc & "\" & svenme & ".pdf"

        ThisWorkbook.FollowHyperlink (url)
        'code to open and save the pdf goes here

    i = i + 1

Loop

Any help gratefully received as I'm really stumped on this one. TIA.


Solution

  • Inspired by KJ's answer, without error checking etc. Just wanted to illustrate how you'd use shell to automate the entire process.

    sveloc = Application.ActiveWorkbook.Path & "\Saved EPCs"
    
    edgePath = Environ$("PROGRAMFILES(X86)") & "\Microsoft\Edge\Application\msedge.exe"
    
    With CreateObject("WScript.Shell")
        i = 7
        Do Until Len(sh01.Cells(i, 27)) = 0 'all cells in the list are populated with no gaps
            On Error Resume Next
            .Run """" & edgePath & """ --profile-directory=Default --headless -print-to-pdf=""" & sveloc & "\" & sh01.Cells(i, 2) & ".pdf" & """ """ & sh01.Cells(i, 27) & """", 1, True
            On Error GoTo 0
            i = i + 1
        Loop
    End With