Search code examples
excelvba

Download & rename file from URL through macro in excel


I need to download a list of dropbox images links and want to rename the files with new name.

What I want to achieve is if i put the new file name in one cell and the link in the another one it should download the file, rename it and save at the file path mentioned in the FILE PATH to save. If there is any error while downloading the image the status will be updated in the status cell.

For Example:

enter image description here

I will be using this macro on MS Office professional plus 2016 64 bit Win 10.

I am trying the below macro but it is not saving the image:

Option Explicit

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

Dim Ret As Long

'~~> This is where the images will be saved. Change as applicable
Const FolderName As String = "C:\Temp\"

Sub Sample()
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String

    '~~> Name of the sheet which has the list
    Set ws = Sheets("Sheet1")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRow '<~~ 2 because row 1 has headers
        strPath = FolderName & ws.Range("A" & i).Value & ".jpg"

        Ret = URLDownloadToFile(0, ws.Range("B" & i).Value, strPath, 0, 0)

        If Ret = 0 Then
            ws.Range("C" & i).Value = "File successfully downloaded"
        Else
            ws.Range("C" & i).Value = "Unable to download the file"
        End If
    Next i
End Sub

Any help will be appreciated.


Solution

  • Could be an issue with the function declaration for 64bit. Try

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

    Update: If the download fails, the function returns an error code. However, if the file can be downloaded but cannot be written locally (eg invalid filename, no write permission...), the function returns 0.