excel - 网页下载图片并保存到文件夹
问题描述
我正在尝试使用 VBA-Web 库(https://github.com/VBA-tools/VBA-Web)下载图像并将其保存到我的计算机。
这段代码工作正常,但我想检查它完成工作的正确方法。VBA 不是我的主要经验。
Sub Run()
Dim client As New WebClient
With client
.BaseUrl = "http://chart.apis.google.com/chart?cht=qr&chs=160x160&chld=L|0&chl=hello"
.EnableAutoProxy = True
End With
Dim request As New WebRequest
With request
.Method = WebMethod.HttpGet
.AddHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
End With
Dim Response As WebResponse
Set Response = client.Execute(request)
ProcessResponse Response
End Sub
Sub ProcessResponse(Response As WebResponse)
Dim oStream As Object
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write Response.Body
oStream.SaveToFile Environ("USERPROFILE") & "\Desktop\image_test.png", 2
oStream.Close
End Sub
我使用了各种其他方法来下载和工作,包括 XMLHTTP 和 URLDownloadToFile,但由于网络问题,我需要 VBA-Web 提供的代理处理......
解决方案
无需使用自定义库,试试这个
Public 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
Public Sub GURoL(url As String, FileName As String)
Dim lngRetVal As Long
lngRetVal = URLDownloadToFile(0, url, FileName, 0, 0)
If lngRetVal <> 0 Then
MsgBox "GURol godo: Can't download from " & url & " to " & FileName
End If
End Sub
Sub Download_Procedure()
Call GURoL("http://i.msdn.microsoft.com/ms348103.LOGO_WINDOWS(en-us,MSDN.10).png", _
"c:\Temp\plik.png") '<change your dest. path
End Sub