Multiple Apps

Save Internet File using XMLHTTP Object

Ease of Use

Intermediate

Version tested with

2000 

Submitted by:

mvidas

Description:

This function allows you to save an external internet file without using API calls or the Internet Explorer object. 

Discussion:

Send to the function the internet address of the file you want to download, as well as the location on your system that you want to save it to, and it uses the Microsoft XML object to download the file to your system. This is just an alternative to using the URLDownloadToFile API call. 

Code:

instructions for use

			

Option Explicit Function SaveWebFile(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 Sub TestingTheCode() 'This will save the Google logo to your hard drive, insert it into the ' active spreadsheet, then delete the local file SaveWebFile "http://www.google.com/intl/en/images/logo.gif", "C:\GoogleLogo.gif" ActiveSheet.Pictures.Insert "C:\GoogleLogo.gif" Kill "C:\GoogleLogo.gif" End Sub

How to use:

  1. Press Alt-F11 from Excel to open the Visual Basic for Applications Editor Window
  2. Go to Insert, then Module
  3. In the blank code pane that appears, paste the code above
  4. Go to File, then Close, to close the VBA Editor
 

Test the code:

  1. Open the sample spreadsheet
  2. Click the command button to run the TestingTheCode subroutine above
 

Sample File:

SaveWebFileExample.zip 10.66KB 

Approved by mdmackillop


This entry has been viewed 338 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express