gpt4 book ai didi

vba - 从 Web 下载文件 (PDF)

转载 作者:行者123 更新时间:2023-12-04 20:18:22 25 4
gpt4 key购买 nike

我是 VBA 的新手。
如何使用 UrlDownloadToFile 从 http://cetatenie.just.ro/wp-content/uploads/ 下载 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

最佳答案

抱歉 - 我应该猜到 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

现在将 Sample 中的那一行更改为如下所示
Ret = URLDownloadToFile(0, sUrl & hAnchor.pathname, sPath & hAnchor.pathname, 0, 0)

那么你应该很高兴。如果您想要一些不同的文件名,那么您必须编写一些逻辑来在每次迭代时更改它。

关于vba - 从 Web 下载文件 (PDF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com