Download Google Drive File from Excel Sheet using VBA - excel

The hyperlink below appears in a cell in an Excel Sheet. It opens and displays a file if clicked on (permissions given to anyone with the link)
How can I download a linked file to a local folder using Excel vba?

URLDownloadToFile on Google Drive
The folder C:\Test has to exist for this example to work.
For more info on URLDownloadToFile try to search SO or Google.
The Code
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 LongPtr, 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
Function downloadFile( _
ByVal FileURL As String, _
ByVal FilePath As String) _
As Boolean
Const ProcName As String = "downloadFile"
On Error GoTo clearError
URLDownloadToFile 0, FileURL, FilePath, 0, 0
downloadFile = True
ProcExit:
Exit Function
clearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Function
Sub downloadGoogleDrive()
Const UrlLeft As String = "http://drive.google.com/u/0/uc?id="
Const UrlRight As String = "&export=download"
Const FileID As String = "17bw2KgzD1ifcA7rdXdxiN9bN70g8jnMO"
Const FilePath As String _
= "C:\Test\Type1 and Type 2 errors - Atyati Temp.jpg"
Dim Url As String: Url = UrlLeft & FileID & UrlRight
Dim wasDownloaded As Boolean
wasDownloaded = downloadFile(Url, FilePath)
If wasDownloaded Then
MsgBox "Success"
Else
MsgBox "Fail"
End If
End Sub

Download File from Google Drive with original file name
Sub DownloadGoogleDriveWithFilename()
Dim myOriginalURL As String
Dim myURL As String
Dim FileID As String
Dim xmlhttp As Object
Dim FolderPath As String
Dim FilePath As String
Dim name0 As Variant
Dim oStream As Object
Dim wasDownloaded As Boolean
Application.ScreenUpdating = False
''URL from share link or Google sheet URL or Google doc URL
myOriginalURL = "https://drive.google.com/file/d/1MnaC9-adPeEjkv7AEARchoYLLSWELBsy/view?usp=sharing"
FileID = Split(myOriginalURL, "/d/")(1) ''split after "/d/"
FileID = Split(FileID, "/")(0) ''split before "/"
Const UrlLeft As String = "http://drive.google.com/u/0/uc?id="
Const UrlRight As String = "&export=download"
myURL = UrlLeft & FileID & UrlRight
Debug.Print myURL
Set xmlhttp = CreateObject("winhttp.winhttprequest.5.1")
xmlhttp.Open "GET", myURL, False ', "username", "password"
xmlhttp.Send
name0 = xmlhttp.getResponseHeader("Content-Disposition")
If name0 = "" Then
MsgBox "file name not found"
Exit Sub
End If
Debug.Print name0
name0 = Split(name0, "=""")(1) ''split after "=""
name0 = Split(name0, """;")(0) ''split before "";"
' name0 = Replace(name0, """", "") ' Remove double quotes
Debug.Print name0
FolderPath = ThisWorkbook.path
FilePath = FolderPath & "\" & name0
''This part is equvualent to URLDownloadToFile(0, myURL, FolderPath & "\" & name0, 0, 0)
''just without having to write Windows API code for 32 bit and 64 bit.
If xmlhttp.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write xmlhttp.responseBody
oStream.SaveToFile FilePath, 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
Application.ScreenUpdating = True
If FileExists(FilePath) Then
wasDownloaded = True
''open folder path location to look at the downloded file
Call Shell("explorer.exe" & " " & FolderPath, vbNormalFocus)
Else
wasDownloaded = False
MsgBox "failed"
End If
End Sub
Function FileExists(FilePath As String) As Boolean
Dim TestStr As String
TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
FileExists = False
Else
FileExists = True
End If
End Function

Related

file not found error on MacOS when trying to download images from url placed in column in excel sheet

I am trying to download all jpg files whose url are placed in an excel sheet in one columns. I am having an error error 53 in mac its 64 bit version. Would changing long variable type to longptr help?
Here is my code
`Option Explicit
Private Declare PtrSafe 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 LongPtr
Public Function DownloadURLtoFile(sSourceURL As String, _
sLocalFileName As String) As Boolean
Debug.Print sSourceURL
Debug.Print sLocalFileName
DownloadURLtoFile = URLDownloadToFile(0&, _
sSourceURL, sLocalFileName, &H10, 0&) = 0&
End Function
Sub DownLoadFiles()
Dim cell As Range, rngListOfURL As Range, FirstName As String, LastName As String, spacepos As Integer, lastrow As Long
Dim FolderName As String, FolderString As String
FolderName = ThisWorkbook.Worksheets("CANDIDATURE").Range("B2").Value & "_" & ThisWorkbook.Worksheets("CANDIDATURE").Range("A2").Value 'Choose Folder Name
FolderString = CreateFolderinMacOffice(NameFolder:=FolderName) 'Create Folder
FolderString = FolderString & Application.PathSeparator
'Const PTH = FolderString & Application.PathSeparator 'this is your save to location
lastrow = ThisWorkbook.Worksheets("CANDIDATURE").Range("C999999").End(xlUp).Row
'Set rngListOfURL = ThisWorkbook.Worksheets("database").Range("AL2:AL26") 'amend as appropriate
Set rngListOfURL = ThisWorkbook.Worksheets("CANDIDATURE").Range("I2", Range("I" & lastrow)) 'amend as appropriate
Debug.Print rngListOfURL.Address
i = 2
For Each cell In rngListOfURL
LastName = ThisWorkbook.Worksheets("CANDIDATURE").Cells(i, 6).Value
FirstName = ThisWorkbook.Worksheets("CANDIDATURE").Cells(i, 5).Value
spacepos = InStr(1, LastName, " ")
If spacepos <> 0 Then
LastName = Left(LastName, spacepos - 1)
End If
Debug.Print cell.Address
If DownloadURLtoFile(cell.Value, FolderString & FirstName & "_" & LastName & ".jpg") Then
cell.Offset(, 3).Value = "Successfully downloaded"
Else
cell.Offset(, 3).Value = "Error - no download"
End If
i = i + 1
Next cell
End Sub
Function CreateFolderinMacOffice(NameFolder As String) As String
'Function to create folder if it not exists in the Microsoft Office Folder
Dim OfficeFolder As String
Dim PathToFolder As String
Dim TestStr As String
OfficeFolder = MacScript("return POSIX path of (path to desktop folder) as string")
OfficeFolder = Replace(OfficeFolder, "/Desktop", "") & _
"Library/Group Containers/UBF8T346G9.Office/"
'OfficeFolder = "C:\Users\Dell\Desktop\New folder\"
PathToFolder = OfficeFolder & NameFolder
Debug.Print PathToFolder
On Error Resume Next
TestStr = Dir(PathToFolder & "*", vbDirectory)
On Error GoTo 0
If TestStr = vbNullString Then
MkDir PathToFolder
'You can use this msgbox line for testing if you want
'MsgBox "You find the new folder in this location :" & PathToFolder
End If
CreateFolderinMacOffice = PathToFolder
End Function
`
My SheetName is "CANDIDATURE" and URL of Images are Placed in Column I (URL of images) of sheet. The Names of the images would be the name in column F (LastName) & Column E (First Name). The images would be placed in a folder which would be named with column B (Person to which task is assigned) and A (Date). I dont have any experience of VBA in Mac so please leave suggestions.

Getting password protected PDF total page numbers into excel

I have a list of PDF files saved in a folder, and I am trying to get the total page number of each PDF file and save it to an excel spreadsheet.
The code works fine with normal PDF files, but the code would not work and return total page number = 0 when the PDFs is password protected, does anyone know how to get around this?
Option Explicit
Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long
Public Function ClearClipboard()
OpenClipboard (0&)
EmptyClipboard
CloseClipboard
End Function
Sub CountPages()
Dim MyPath As String, MyFile As String
Dim i As Long
MyPath = Cells(1, 7)
MyFile = Dir(MyPath & Application.PathSeparator & "*.pdf", vbDirectory)
Range("A:B").ClearContents
Range("A1") = "File Name": Range("B1") = "Pages"
Range("A1:B1").Font.Bold = True
i = 1
Do While MyFile <> ""
i = i + 1
Cells(i, 1) = MyFile
Cells(i, 2) = GetPageNum(MyPath & Application.PathSeparator & MyFile)
MyFile = Dir
Loop
Columns("A:B").AutoFit
MsgBox "Total of " & i - 1 & " PDF files have been found" & vbCrLf _
& " File names and corresponding count of pages have been written on " _
& ActiveSheet.Name, vbInformation, "Report..."
End Sub
Function GetPageNum(PDF_File As String)
Dim FileNum As Long
Dim strRetVal As String
Dim RegExp
Set RegExp = CreateObject("VBscript.RegExp")
RegExp.Global = True
RegExp.Pattern = "/Type\s*/Page[^s]"
FileNum = FreeFile
Open PDF_File For Binary As #FileNum
strRetVal = Space(LOF(FileNum))
Get #FileNum, , strRetVal
Close #FileNum
GetPageNum = RegExp.Execute(strRetVal).Count
End Function

Download CSV File from GitHub

I am trying to load csv file and download it to my hard disk from a link of GitHub. Here's my try
#If Win64 Then
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As LongLong, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As LongLong, ByVal lpfnCB As LongLong) As LongLong
#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
Function DownloadFile(Url As String, SavePathName As String) As Boolean
DownloadFile = URLDownloadToFile(0, Replace(Url, "\", "/"), SavePathName, 0, 0) = 0
End Function
Sub Demo()
Dim strUrl As String, strSavePath As String, strFile As String
strUrl = "https://github.com/pcm-dpc/COVID-19/blob/master/dati-regioni/dpc-covid19-ita-regioni-20200224.csv" 'SharePoint Path For The File
strSavePath = ThisWorkbook.Path & "\"
strFile = "FileName" & Format(Date, "dd.mm.yyyy") & ".csv"
If DownloadFile(strUrl, strSavePath & strFile) Then
MsgBox "File Saved To: " & vbNewLine & strSavePath
Else
MsgBox "Unable To Download File:" & vbNewLine & strFile & vbNewLine & "Check URL String And That Document Is Shared", vbCritical
End If
End Sub
I used the code before to download some files and it worked well but as for this link the downloaded file is as HTML page not csv file. How can I download it as CSV file?
Try hitting the raw content option on that page. The link you are hitting has HTML markup, the other is just the CSV content.
Option Explicit
Public Sub GetCSV()
Dim response As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni-20200224.csv", False
.Send
response = .responseText
End With
If Trim$(response) = "" Then Exit Sub
Open "YOURPATHHERE\SOMEFILE.csv" For Output As #1
Print #1, response
Close #1
End Sub
this is more simple.
cange website address.
Sub test()
Dim Whttp As WinHttp.WinHttpRequest
Dim strFile As String, str As String
Dim Url As String
Set Whttp = New WinHttp.WinHttpRequest
Url = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni-20200224.csv" 'SharePoint Path For The File
strSavePath = ThisWorkbook.Path & "\"
strFile = strSavePath & "FileName" & Format(Date, "dd.mm.yyyy") & ".csv"
With Whttp
.Open "Get", Url
.send
str = .responseText
End With
TransToCSV strFile, str
End Sub
Sub TransToCSV(myfile As String, strTxt As String)
Dim objStream As Object
Set objStream = CreateObject("ADODB.Stream")
With objStream
.Charset = "utf-8"
.Open
.WriteText strTxt
.SaveToFile myfile, 2
.Close
End With
Set objStream = Nothing
End Sub

Losing data through csv file opening loop vba

I got CSV dataset every day from 5 partners after 8PM. The files are in the same structure, the range of the size 4- 130 KB in the same folder. I want to merge all files to one by macro, the today result is days from 10-15th are missing. Data of 16th (the last day) are good. When I run the macro for only one partner, I get full result. What can be the problem?
Dim MyFolder As String
Dim MyFile As String
Dim last As Integer
Dim newrow As Integer
Dim sh As Worksheet
Dim name As String
Dim name2 As String
Dim myYear As Variant
Dim myMonth As Variant
Sheets("Munka1").Select
name = ActiveWorkbook.name
ScreenUpdating = False
Range(Cells(2, 1), Cells(300000, 200)).Select
Selection.Clear
Cells(2, 1).Select
MyFolder = "InputFolder"
MyFile = Dir(MyFolder & "\FILE_*" & "*.csv")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile, Local:=True
name2 = ActiveWorkbook.name
On Error Resume Next
Range(Cells(2, 1), Cells(3000, 11)).Select
Selection.Copy
Windows(name).Activate
Cells(newrow, 1).Select
ActiveSheet.Paste
last= Range("A1", Range("A1").End(xlDown)).Rows.Count
newrow = last + 1
Application.CutCopyMode = False
Windows(name2).Close savechanges:=False
MyFile = Dir
Loop
Can you try it like this and feedback?
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Private Declare PtrSafe Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, _
lpExitCode As Long) As Long
#Else
Private Declare Function OpenProcess Lib "kernel32" _
(ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" _
(ByVal hProcess As Long, _
lpExitCode As Long) As Long
#End If
Public Const PROCESS_QUERY_INFORMATION = &H400
Public Const STILL_ACTIVE = &H103
Public Sub ShellAndWait(ByVal PathName As String, Optional WindowState)
Dim hProg As Long
Dim hProcess As Long, ExitCode As Long
'fill in the missing parameter and execute the program
If IsMissing(WindowState) Then WindowState = 1
hProg = Shell(PathName, WindowState)
'hProg is a "process ID under Win32. To get the process handle:
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, False, hProg)
Do
'populate Exitcode variable
GetExitCodeProcess hProcess, ExitCode
DoEvents
Loop While ExitCode = STILL_ACTIVE
End Sub
Sub Merge_CSV_Files()
Dim BatFileName As String
Dim TXTFileName As String
Dim XLSFileName As String
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim DefPath As String
Dim Wb As Workbook
Dim oApp As Object
Dim oFolder
Dim foldername
'Create two temporary file names
BatFileName = Environ("Temp") & _
"\CollectCSVData" & Format(Now, "dd-mm-yy-h-mm-ss") & ".bat"
TXTFileName = Environ("Temp") & _
"\AllCSV" & Format(Now, "dd-mm-yy-h-mm-ss") & ".txt"
'Folder where you want to save the Excel file
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
'Set the extension and file format
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007 or higher
FileExtStr = ".xlsx": FileFormatNum = 51
'If you want to save as xls(97-2003 format) in 2007 use
'FileExtStr = ".xls": FileFormatNum = 56
End If
'Name of the Excel file with a date/time stamp
XLSFileName = DefPath & "MasterCSV " & _
Format(Now, "dd-mmm-yyyy h-mm-ss") & FileExtStr
'Browse to the folder with CSV files
Set oApp = CreateObject("Shell.Application")
Set oFolder = oApp.BrowseForFolder(0, "Select folder with CSV files", 512)
If Not oFolder Is Nothing Then
foldername = oFolder.Self.Path
If Right(foldername, 1) <> "\" Then
foldername = foldername & "\"
End If
'Create the bat file
Open BatFileName For Output As #1
Print #1, "Copy " & Chr(34) & foldername & "*.csv" _
& Chr(34) & " " & TXTFileName
Close #1
'Run the Bat file to collect all data from the CSV files into a TXT file
ShellAndWait BatFileName, 0
If Dir(TXTFileName) = "" Then
MsgBox "There are no csv files in this folder"
Kill BatFileName
Exit Sub
End If
'Open the TXT file in Excel
Application.ScreenUpdating = False
Workbooks.OpenText Filename:=TXTFileName, Origin:=xlWindows, StartRow _
:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=True, _
Space:=False, Other:=False
'Save text file as a Excel file
Set Wb = ActiveWorkbook
Application.DisplayAlerts = False
Wb.SaveAs Filename:=XLSFileName, FileFormat:=FileFormatNum
Application.DisplayAlerts = True
Wb.Close savechanges:=False
MsgBox "You find the Excel file here: " & vbNewLine & XLSFileName
'Delete the bat and text file you temporary used
Kill BatFileName
Kill TXTFileName
Application.ScreenUpdating = True
End If
End Sub
https://www.rondebruin.nl/win/s3/win021.htm
I just had to change last and newraw variable to long.

NOT A DUPLICATE - How to Set File Path in Window Explorer After Downloading File From IE [duplicate]

I need to download a CSV file from a website using VBA in Excel. The server also needed to authenticate me since it was data from a survey service.
I found a lot of examples using Internet Explorer controlled with VBA for this. However, it was mostly slow solutions and most were also convoluted.
Update:
After a while I found a nifty solution using Microsoft.XMLHTTP object in Excel. I thought to share the solution below for future reference.
This solution is based from this website:
http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url
It is slightly modified to overwrite existing file and to pass along login credentials.
Sub DownloadFile()
Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub
Declare PtrSafe 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
Sub Example()
DownloadFile$ = "someFile.ext" 'here the name with extension
URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub
Source
I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.
This was helpful because our organization has Kaspersky AV which blocks active FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!
A modified version of above to make it more dynamic.
Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
On Error GoTo Failed
Dim WinHttpReq As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URL, False, Username, Password
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Dim oStream As Object: Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
oStream.Close
DownloadFileB = Len(Dir(DownloadPath)) > 0
Exit Function
End If
Failed:
DownloadFileB = False
End Function
I was struggling for hours on this until I figured out it can be done in one line of powershell:
invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials
I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.
Simple.
Public Sub Test_DownloadFile()
Dim URLStr As String, DLPath As String, UName As String, PWD As String, DontOverWrite As Boolean
URLStr = "http.."
DLPath = Environ("USERPROFILE") & "\Downloads\TEST.PDF"
UName = ""
PWD = ""
DontOverWrite = False
Call DownloadFile(URLStr, DLPath, UName, PWD, DontOverWrite)
End Sub
Public Sub DownloadFile(ByVal URLStr As String, ByVal DLPath As String, Optional ByVal UName As String, Optional ByVal PWD As String, Optional DontOverWrite As Boolean)
On Error GoTo Failed
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URLStr, False, UName, PWD
WinHttpReq.send
If WinHttpReq.status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
Dim OWrite As Integer
If DontOverWrite = True Then
OWrite = 1
Else
OWrite = 2
End If
oStream.SaveToFile DLPath, OWrite
oStream.Close
Debug.Print "Downloaded " & URLStr & " To " & DLPath
Exit Sub
End If
Failed:
Debug.Print "Failed to DL " & URLStr
End Sub
A modified version of above solution to make it more dynamic.
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
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
On Error GoTo Failed
DownloadFileA = False
'As directory must exist, this is a check
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
Dim returnValue As Long
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
'If return value is 0 and the file exist, then it is considered as downloaded correctly
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
Exit Function
Failed:
End Function

Resources