Want to become an expert in VBA? So this is the right place for you. This blog mainly focus on teaching how to apply Visual Basic for Microsoft Excel. So improve the functionality of your excel workbooks with the aid of this blog. Also ask any questions you have regarding MS Excel and applying VBA. We are happy to assist you.

Download a file from url using VBA

Sometimes our VB Applications needs to interact with websites. Downloading a file through a url is a typical example.

Here below is a code which you can use to download a file through a url. You should replace "Put your download link here" with your url. Also remember to put it inside double quotes.

Dim myURL As String
myURL = "Put your download link here"

Dim HttpReq As Object
Set HttpReq = CreateObject("Microsoft.XMLHTTP")
HttpReq.Open "GET", myURL, False, "username", "password"
HttpReq.send

myURL = HttpReq.responseBody
If HttpReq.Status = 200 Then
    Set oStrm = CreateObject("ADODB.Stream")
    oStrm.Open
    oStrm.Type = 1
    oStrm.Write HttpReq.responseBody
    oStrm.SaveToFile ThisWorkbook.Path & "\" & "file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStrm.Close
End If

Also you should be careful with below line.

 oStrm.SaveToFile ThisWorkbook.Path & "\" & "file.csv", 2 ' 1 = no overwrite, 2 = overwrite

In this case I have chosen the option to overwrite existing file. If you don't need to overwrite existing file please put the number accordingly.

Contact Form

Name

Email *

Message *

Popular Posts