

In between the chunks you can call “DoEvents” to enable user interaction, inform the user of the download progress Application.StatusBar or do other thing including interrupting the process and closing the connection. The procedure will download the binary file in 128 byte chunks while saving the contents to the data stream and flushing it into the file once completed. See effect below when executing macro: How it works OStream.SaveToFile filePath, IIf(overWriteFile, 2, 1) " & CLng(totalRead / 1024) & " KB downloaded"Īpplication.StatusBar = "Download complete" ReDim Preserve sBuffer(lngDataReturned - 1)Īpplication.StatusBar = "Downloading file. IReadFileResult = InternetReadBinaryFile(hInternet, sBuffer(0), UBound(sBuffer) - LBound(sBuffer), lngDataReturned) Set oStream = CreateObject("ADODB.Stream")

If hSession Then hInternet = InternetOpenUrl(hSession, sUrl, vbNullString, 0, INTERNET_FLAG_NO_CACHE_WRITE, 0) HSession = InternetOpen("", 0, vbNullString, vbNullString, 0) Sub DownloadFile(sUrl As String, filePath As String, Optional overWriteFile As Boolean)ĭim hInternet, hSession, lngDataReturned As Long, sBuffer() As Byte, totalRead As Long Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long) As Integer Private Declare Function InternetOpenUrl Lib "wininet.dll" Alias "InternetOpenUrlA" (ByVal hInternetSession As Long, ByVal sUrl As String, ByVal sHeaders As String, ByVal lHeadersLength As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long Private Declare Function InternetReadBinaryFile Lib "wininet.dll" Alias "InternetReadFile" (ByVal hfile As Long, ByRef bytearray_firstelement As Byte, ByVal lNumBytesToRead As Long, ByRef lNumberOfBytesRead As Long) As Integer

Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" (ByVal lpszAgent As String, ByVal dwAccessType As Long, ByVal lpszProxyName As String, ByVal lpszProxyBypass As String, ByVal dwFlags As Long) As Long Private Const INTERNET_FLAG_NO_CACHE_WRITE = &H4000000 The procedure below may however prove more efficient as it will download the file in 128 byte chunks of data instead of a single stream. In these cases the above procedure won’t do. might want to interrupt the process, enable the user to interact with Excel (DoEvent) etc. In some cases you will need to download large files (not text/HTML) and will want to be able to control the process of downloading the data e.g.
