Const INTERNET_OPEN_TYPE_PRECONFIG = 0 Const INTERNET_FLAG_EXISTING_CONNECT = &H20000000
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 Declare Function InternetOpenUrl Lib "wininet.dll" Alias _ "InternetOpenUrlA" (ByVal hInternetSession As Long, ByVal lpszUrl As String, _ ByVal lpszHeaders As String, ByVal dwHeadersLength As Long, _ ByVal dwFlags As Long, ByVal dwContext As Long) As Long Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As _ Long) As Integer Private Declare Function InternetReadFile Lib "wininet.dll" (ByVal hFile As _ Long, ByVal lpBuffer As String, ByVal dwNumberOfBytesToRead As Long, _ lNumberOfBytesRead As Long) As Integer
Sub CopyURLToFile(ByVal URL As String, ByVal FileName As String) Dim hInternetSession As Long Dim hUrl As Long Dim FileNum As Integer Dim ok As Boolean Dim NumberOfBytesRead As Long Dim Buffer As String Dim fileIsOpen As Boolean
On Error GoTo ErrorHandler
If Len(URL) = 0 Or Len(FileName) = 0 Then Err.Raise 5
hInternetSession = InternetOpen(App.EXEName, INTERNET_OPEN_TYPE_PRECONFIG, _ vbNullString, vbNullString, 0) If hInternetSession = 0 Then Err.Raise vbObjectError + 1000, , _ "An error occurred calling InternetOpen function"
hUrl = InternetOpenUrl(hInternetSession, URL, vbNullString, 0, _ INTERNET_FLAG_EXISTING_CONNECT, 0) If hUrl = 0 Then Err.Raise vbObjectError + 1000, , _ "An error occurred calling InternetOpenUrl function"
On Error Resume Next Kill FileName
On Error GoTo ErrorHandler FileNum = FreeFile Open FileName For Binary As FileNum fileIsOpen = True
Buffer = Space(4096) Do ok = InternetReadFile(hUrl, Buffer, Len(Buffer), NumberOfBytesRead)
If NumberOfBytesRead = 0 Or Not ok Then Exit Do Put #FileNum, , Left$(Buffer, NumberOfBytesRead) Loop
ErrorHandler: If fileIsOpen Then Close #FileNum If hUrl Then InternetCloseHandle hUrl If hInternetSession Then InternetCloseHandle hInternetSession If Err Then Err.Raise Err.Number, , Err.Description End Sub |