Monday, 7 February 2011

HTTP File Download using VBA (Password Protected Site)

Recently I embarked on a project involving the file download from a password protected site (http location), though with some troubles to get the Internet Transfer Controls setup on my PC. I found the following solution amazingly brilliant to complete the task.

The following solution uses the Internet Transfer Control object to navigate to the http location using the authentication protocols and details and obtains the files in byte format which is then placed at the location of your choice using the file operation in VBA.

The code is illustrated as follows:

Sub HTTPDownloadFile(ByVal URL As String, ByVal LocalFileName As String)
    Dim HTTP As Inet
    Dim Contents() As Byte

    Set HTTP = New Inet
    With HTTP
        .Protocol = icHTTP
        .URL = URL
        .UserName = "**UserName**"
        .Password = "**Password**"
        Contents() = .OpenURL(.URL, icByteArray)
    End With
    Set HTTP = Nothing

    Open LocalFileName For Binary Access Write As #1
    Put #1, , Contents()
    Close #1
End Sub

Note: To install the Internet Transfer Control for the Vista x64 , Just copy and paste the "msinet.ocx" file into the "C:\Windows\SysWow64" folder and run the "regsvr32" which should successfully install the Internet transfer control on your system.

Office One:

No comments: