excel VBA: Download URL file to local drive

VBA code to download a file from URL address:

Sub DownloadUrlFile()
' Create an array to hold the response data.
Dim arrDownloadedBytes() As Byte
Dim WinHttpReq As WinHttpRequest
Dim strURL, strLocalPath, strLocalFileName As String
strURL = "https://www.xxxx.com/documents/FilenameToDownload"
strLocalPath = "C:\User\documents\"
strLocalFileName = "FilenameDownloaded"
Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
WinHttpReq.SetAutoLogonPolicy (0)
'In case you have V5.0 instead of v5.1 - use this line
'Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.0")
' create the HTTP Request
WinHttpReq.Open "GET", strURL, False
' Send the request
' copy the response body to a local file
Open strLocalPath & strLocalFileName For Binary As #1
arrDownloadedBytes() = WinHttpReq.ResponseBody
Put #1, 1, arrDownloadedBytes()
End Sub

Leave a Reply