2013-03-26 121 views
2

我是VBA的新手入门者。 如何使用UrlDownloadToFile从http://cetatenie.just.ro/wp-content/uploads/下载PDF文件?从网上下载文件(PDF)

任何人都可以帮忙吗?该代码正在搜索PDF文件udner超链接,并在某些标准下匹配它们,即以它们名下的当年。

Function UrlDownloadToFile(lNum As Long, sUrl As String, sPath As String, _ 
          lNum1 As Long, lNum2 As Long) As Long 

    UrlDownloadToFile = 0 

    End Function 

Sub DownPDF() 
    ' This macro downloads the pdf file from webpage 
    ' Need to download MSXML2 and MSHTML parsers and install 

    Dim sUrl As String 
    Dim xHttp As MSXML2.XMLHTTP 
    Dim hDoc As MSHTML.HTMLDocument 
    Dim hAnchor As MSHTML.HTMLAnchorElement 
    Dim Ret As Long 
    Dim sPath As String 
    Dim i As Long 

    sPath = "C:\Documents and Settings\ee28118\Desktop\" 
    sUrl = "http://cetatenie.just.ro/wp-content/uploads/" 

    'Get the directory listing 
    Set xHttp = New MSXML2.XMLHTTP 
    xHttp.Open "GET", sUrl 
    xHttp.send 

    'Wait for the page to load 
    Do Until xHttp.readyState = 4 
     DoEvents 
    Loop 

    'Put the page in an HTML document 
    Set hDoc = New MSHTML.HTMLDocument 
    hDoc.body.innerHTML = xHttp.responseText 

    'Loop through the hyperlinks on the directory listing 
    For i = 0 To hDoc.getElementsByTagName("a").Length - 1 
     Set hAnchor = hDoc.getElementsByTagName("a").Item(i) 

     'test the pathname to see if it matches your pattern 
     If hAnchor.pathname Like "Ordin-*.2013.pdf" Then 
      Ret = UrlDownloadToFile(0, sUrl & hAnchor.pathname, sPath, 0, 0) 

      If Ret = 0 Then 
       Debug.Print sUrl & hAnchor.pathname & " downloaded to " & sPath 
      Else 
       Debug.Print sUrl & hAnchor.pathname & " not downloaded" 
      End If 
     End If 
    Next i 

    End Sub 
+0

UrlDownloadtoFile是一个Win API函数:http://www.vbaexpress.com/forum/showthread.php?t=33145你需要调用它,而不是递归调用你发布的函数。 – 2013-03-26 16:10:54

回答

2

对不起 - 我应该能猜到URLDownloadToFile是一个API调用,并在SQL "%" equivalent in VBA可能已经回答了全部问题。

完全删除名为URLDownloadToFile的函数。在您的示例程序是

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 

现在更改一行在样品看起来像这样

Ret = URLDownloadToFile(0, sUrl & hAnchor.pathname, sPath & hAnchor.pathname, 0, 0) 

那你应该是好去在模块的顶部粘贴此。如果你想要一些不同的文件名,那么你必须编写一些逻辑来在每次迭代中改变它。

+0

令人惊叹!!! Everyting很好,实际上是完美的,谢谢你的所有帮助! – maximladus 2013-03-27 08:51:58