Variatus
Variatus

Reputation: 14373

VBA to download an image from an Internet source

I want to download an image from the web and tried using the URLDownloadToFile API as follows.

#If VBA7 Then
    Private Declare Function URLDownloadToFile Lib "urlmon" _
                             Alias "URLDownloadToFileA" ( _
                             ByVal pCaller As LongPtr, _
                             ByVal szURL As String, _
                             ByVal szFileName As String, _
                             ByVal dwReserved As LongPtr, _
                             ByVal lpfnCB As LongPtr) _
                             As Long
#Else
    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
#End If

    Private Sub TestDownload()

        Dim Source As String, Target As String
        Dim Ret As Long

        Source = "//cdnparap40.paragonrels.com/ParagonImages/Property/P4/JONESBORO/10077581/0/120/90/" & _
                 "f645b5257c6ae2f13147ec57c315f9f4/1/acd2b86d15f1087ed3462f2ba4ebb733/10077581.JPG"
        Target = "H:\Temp\FileName.jpg"
        Ret = URLDownloadToFile(0, Source, Ffn, 0, 0)
    End Sub

The target directory exists but the code delivers no result (Ret = 0). However, I don't know the reason as there is no error from the code.

The Internet address is correct. I can view the picture and its open to the public. However, I am not sure that downloading is permitted.

I don't know if a specific reference to Urlmon.dll is required. I tried to load it but VBA (Excel 2010) refused, "can't add a reference to the specified library".

VBA7 = True on my machine. I changed the 3 Long declarations to LongPtr but I'm not aware that this is required (for all three). Before I tried the same code with Long declarations with no better result.

Last, not least, I'm not sure that URLDownloadToFileA is the API to use for this purpose with this particular structure of URL. Perhaps there is an even simpler solution.

Any guidance is welcome, a solution would be awesome. Thank you.

Upvotes: 0

Views: 447

Answers (1)

FunThomas
FunThomas

Reputation: 29171

If you enter the image-url without protocol in the browser, the browser chooses the default protocol (usually http). But this seems not the case for the URLDownloadToFile-function.

Adding a leading http: to the url did the trick for me

Upvotes: 1

Related Questions