Forum Discussion
drnick66
Apr 25, 2020Copper Contributor
save an image from a URL in excel
Hi Sorry to have to ask such a basic question, but I simply can't work out how to do this. I have a column of URLs that link to images, all I want to do is to download all of these images and sav...
- Apr 25, 2020
drnick66 hello there!
I wouldn't qualify the question as "basic". It's a little advanced with VBA I'd say. Below is an example of how you can download a list of files via their URL. It will save the name with the same name it has on the web. Note there are no checks to see if the file exists and the destination folder is hard-coded (change to desired).
Option Explicit #If VBA7 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 Public Sub DownloadImages() Dim Downloaded As Boolean Dim Count As Long Dim Index As Long Dim FileName As String Dim NameParts As Variant Dim Values As Variant Const DownloadPath As String = "C:\Users\Zack\Desktop\" Values = ThisWorkbook.Worksheets("Sheet1").Range("A2:A6").Value For Index = LBound(Values, 1) To UBound(Values, 1) NameParts = Split(Values(Index, 1), "/") FileName = NameParts(UBound(NameParts)) Downloaded = URLDownloadToFile(0, Values(Index, 1), DownloadPath & FileName, 0, 0) = 0 If Downloaded Then Count = Count + 1 Next Index MsgBox Count & " files out of " & UBound(Values, 1) - LBound(Values, 1) + 1 & " downloaded." End SubHTH