I am trying to download historical stock price data from finance.yahoo.com for 1000s of stocks. The website only displays 60 days of data on a single page so I have to loop through the time period that I am downloading for along with the loop for different securities. I have used the following code to access the relevant page.
Set httpObject = CreateObject("MSXML2.XMLHTTP")
httpObject.Open "GET", url, False
httpObject.send
webObject.body.innerHTML = httpObject.responseText
This works like a charm for 99% of the data that I access. But every now and then, the object returned by the website turns out to be empty, even though the exact same URL will show me the correct data in Internet Explorer. If I rerun the code for just that URL, it may or may not fail the next time.
I would like to know if there is a more stable/consistent way of using the above method. I had previously implemented the InternetExplorer.Application method to download data but found that to be much slower and cumbersome.
XmlHttpRequest – Http requests in Excel VBA Ranjith kumarJune 24, 2016131 CommentscodingExcelVBA Excel is a powerful and most popular tool for data analysis! HTTP requests in VBA gives additional capabilities to Excel. XmlHttpRequest object is used to make HTTP requests in VBA.
Let’s see how we can pull data from a website into Excel VBA with step-by-step analysis. First of all, we have to set up the environment to pull data. Press ALT+F12 on your keyboard. The Visual Basic window will open. Go to the toolbar at the top and click on Tools > References.
A faster method would be using the MSXML object. The downside of using the MSXML object is that you can’t use it on any site. The MSXML object is actually used to connect to an XML file.
Custom function to encode a string is mention in the article. Then pass the encoded string with header named “Authorization” "Authorization", "Basic " + Base64Encode(user + ":" + password) You may use any client like WinHTTP on XMLHTTP but the “Basic” authentication process remains the same. 0 Reply Marcelo Gazzola Ribeiro 2 years ago
Check the readystate.
httpObject.ReadyState = 4
that means it's done loading. Then you can check the status
httpObject.Status = 200
that means you didn't mess up the URL. If readystate is 4 and status is 200, then you can read the responseText.
I had the same issue, getting an empty repsonse, with .Status = 0
(i.e. Ok).
My issue it turned out was that the http when you go in the browser redirects to https. When I changed it in my request it was fine.
For a generic function, you could try http and if you get .Status = 0
and .responseText = ""
, then repeat but with https.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With