Reputation: 421
I am trying to use the VBA-Web library (https://github.com/VBA-tools/VBA-Web) to download an image and save it to my computer.
This code works fine but I want to check its the right way to get the job done. VBA isn't a my primary experience.
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
I have used various other methods to download and had working including XMLHTTP and URLDownloadToFile but due to network issues I need the proxy handling that VBA-Web offers...
Upvotes: 1
Views: 7170
Reputation: 46
Note: in case you got the error massage "Compile error: The code in this project must be updated for use on 64-bit systems. Please review and update Declare statements and then mark them with the PtrSafe attribute".
Image of this prompted error massage
try add the PtrSafe
keyword to Declare
statement could help.
For example, make change of the above code snippet to be
Public Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias _
This is also working on Excel 2016 64-bit.
Ref: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/ptrsafe-keyword
Upvotes: 1
Reputation: 701
no need to use custom libraries, try this
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
Upvotes: 4