通过URLDownloadToFile自动下载PDF

时间:2017-07-07 13:49:21

标签: excel-vba excel-2007 vba excel

如何从以下代码中的网站而不是blah.pdf中提取PDF的默认名称?

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

1 个答案:

答案 0 :(得分:0)

使用您原始的下载文件的方法很好,但您如何确定路径和文件名?你有名单吗?你需要从网站上获取它吗?关于检索仪器编号,首先将参考(VBE>工具>参考)设置为Microsoft XML,vx.0和Microsoft HTML对象库,然后相应地更改指定的URL,然后尝试...

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