Search code examples
excelexcel-2007vba

Auto Download PDF thru URLDownloadToFile


How do I pull the default name of a PDF from a website instead of blah.pdf in following code?

Option Explicit 

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 z() 

    Dim strSource As String 
    Dim strDest As String 
    strSource = "http://www.cran.r-project.org/doc/manuals/R-intro.pdf" 
    strDest = "c:\temp\blah.pdf" 
    URLDownloadToFile 0, strSource, strDest, 0, 0 

End Sub

Solution

  • Using your original method of downloading the file is fine, but how are you actually determining the path and filename? Do you have a list? Do you need to get it from the website? With regards to retrieving the instrument number, first set references (VBE > Tools > References) to Microsoft XML, vx.0 and Microsoft HTML Object Library, then change the specified URL accordingly, and then try...

    Option Explicit
    
    Sub GetInstrumentNumber()
    
        'Set a reference (VBE > Tools > References) to the following libraries:
        '   1) Microsoft XML, v6.0 (or whatever version you have)
        '   2) Microsoft HTML Object Library
    
        Dim XMLReq As New MSXML2.XMLHTTP60
        Dim HTMLDoc As New MSHTML.HTMLDocument
        Dim sURL As String
        Dim sInstrument As String
    
        sURL = "http://www.cran.r-project.org/..." 'change the URL adddress accordingly
    
        With XMLReq
            .Open "GET", sURL, False
            .send
            Do While .readyState <> 4
                DoEvents
            Loop
        End With
    
        If XMLReq.Status <> 200 Then
            MsgBox "Error " & XMLReq.Status & ":  " & XMLReq.statusText
            Exit Sub
        End If
    
        HTMLDoc.body.innerHTML = XMLReq.responseText
    
        sInstrument = HTMLDoc.getElementById("6063270").getElementsByTagName("tr")(0).Cells(0).innerText
        sInstrument = Trim(Split(sInstrument, ":")(1))
    
        MsgBox "Instrument number:  " & sInstrument, vbInformation
    
        Set XMLReq = Nothing
        Set HTMLDoc = Nothing
    
    End Sub