Unfortunately, MS didn't decide to give us a copy of wget, so we have to write it ourselves. This function uses the XMLHTTP object to download binary files and write them to disk. I don't remember where I found this code, but just for full disclosure, I didn't write it:
Function Download_File(ByVal vWebFile As String, ByVal vLocalFile As String) As Boolean
Dim oXMLHTTP As Object, i As Long, vFF As Long, oResp() As Byte
'You can also set a ref. to Microsoft XML, and Dim oXMLHTTP as MSXML2.XMLHTTP
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP")
oXMLHTTP.Open "GET", vWebFile, False 'Open socket to get the website
oXMLHTTP.Send 'send request
'Wait for request to finish
Do While oXMLHTTP.readyState <> 4
DoEvents
Loop
oResp = oXMLHTTP.responseBody 'Returns the results as a byte array
'Create local file and save results to it
vFF = FreeFile
If Dir(vLocalFile) <> "" Then Kill vLocalFile
Open vLocalFile For Binary As #vFF
Put #vFF, , oResp
Close #vFF
'Clear memory
Set oXMLHTTP = Nothing
End Function
Here's the call that will download a copy of the Tiny Web Server to the %TEMP% directory and use the local installation of Winzip to install it:
Sub Workbook_Open()
'Download tiny web server to the %TEMP% directory, use local copy of winzip to unzip
'Obviously in a real world application you'd want to bring your own unzipper
Download_File "http://www.ritlabs.com/download/tinyweb/tinyweb.zip", Environ("TEMP") & "\tinyweb.zip"
Run_Program "winzip", "-e -o %TEMP%\tinyweb.zip %TEMP%", INVISIBLE, WAIT
End Sub
5 comments:
Thank you for codes.
It works fine. I replaced my wget version with it. It would be better if it support http proxy.
It works fine. Very useful as it was what I was looking for downloading a group of files from a directory via internet.
There is a lot of love here right about now... thanks a LOT!
You can also use WININET to download files in VBA:
http://www.lazerwire.com/2011/11/excel-vba-download-files-from-internet.html
Great, it worked perfectly! Thank you very much for the code!
Post a Comment