在 Outlook 中使用 VBA 在 Web/URL/超链接上保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6350888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using VBA in Outlook to Save File on Web/URL/Hyperlink
提问by SeanJean
So I receive a weekly email that always has the same form and has a hyperlink to a PDF file in the body. I know how to parse the email to retrieve the URL, but is it possible to have VBA code then download that file from the hyperlink/url and save it in a folder?
因此,我每周都会收到一封电子邮件,该电子邮件的格式始终相同,并且正文中包含指向 PDF 文件的超链接。我知道如何解析电子邮件以检索 URL,但是是否可以使用 VBA 代码然后从超链接/url 下载该文件并将其保存在文件夹中?
回答by Tim Williams
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 DownloadFile(sURL, sSaveAs)
Dim rv As Long
rv = URLDownloadToFile(0, sURL, sSaveAs, 0, 0)
If rv = 0 Then
MsgBox "Download has been succeed!"
Else
MsgBox "Error"
End If
End Sub
回答by SeanJean
I ended up using a different method I found on another board, though I know most of the examples I could find used UrlDownloadtoFile. The code is below:
我最终使用了在另一块板上找到的不同方法,尽管我知道我能找到的大多数示例都使用了 UrlDownloadtoFile。代码如下:
Dim myURL As String
myURL = "http://www.somesite.com/file.csv"
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send
myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile ("C:\file.csv")
oStream.Close
End If