Why a macro should fetch its own data
This lesson is for people who already write VBA and are tired of the same weekly routine: open a browser, look up an exchange rate, a stock level, a ticket count or a shipment status, copy it, paste it into a sheet and hope nobody mistyped a digit. Almost every modern system offers a web API, a URL that returns data instead of a web page. If a macro can call that URL itself, the copy and paste disappears, the number arrives with a timestamp, and the report can be refreshed with one click by someone who has never seen the source system.
The catch is that VBA was designed long before web APIs were normal. There is no Http keyword and no JSON type. What VBA does have is access to Windows COM objects, and Windows ships with several that speak HTTP very well. Once you understand the one shape that every web call has, these objects stop being mysterious: you fill in a request, send it, and read the response out of a few properties. This article walks through that shape, the three objects you can choose from, a complete worked call against a placeholder API, the failure cases you have to plan for, and the traps that cost people the most time. The lab above contains a ready-to-run macro that does the same against a free public rate service.
The core idea: a request and a response, nothing more
Every web call, whether it comes from a browser, a phone app or your macro, has the same structure. You send a request made of a method (usually GET to read, POST to send data), a URL, a few headers that describe what you want, and sometimes a body. The server answers with a response made of a status number, its own headers, and a body of text. For an API that body is usually JSON, a compact text format of names and values such as {"rates":{"EUR":1.07}}.
In VBA the COM object sits in the middle. You never open a network socket yourself. You set the method and URL with .Open, add headers with .setRequestHeader, fire it with .send, and then read .Status and .responseText. That is the whole conversation. Everything else in this course, from API keys to retries, is a variation on these five members.
Three objects, and which one to pick
Windows offers three HTTP objects that VBA can create with CreateObject, so you do not need to set a reference under Tools > References. They share almost the same members, which makes it easy to switch, but they behave differently in ways that matter once a macro runs unattended.
| MSXML2.XMLHTTP | MSXML2.ServerXMLHTTP.6.0 | WinHttp.WinHttpRequest.5.1 | |
|---|---|---|---|
| Timeout control | none | setTimeouts (four values in ms) | SetTimeouts (four values in ms) |
| Network stack | WinINET (the old Internet Explorer stack) | WinHTTP | WinHTTP |
| Caches GET replies | yes, can serve a stale answer | no own cache | no own cache |
| Uses the user's proxy and sign-in automatically | yes | not by default | configurable |
| Good for | quick tests on an office PC | unattended report macros (the lab uses it) | fine control: proxy, redirects, certificates |
For report macros the sensible default is MSXML2.ServerXMLHTTP.6.0, the object the lab uses. It has real timeouts and no cache of its own, so the answer you read is the answer the server just gave. Plain XMLHTTP is convenient on an office PC behind a corporate proxy because it borrows the proxy settings and sign-in that Windows already has, but it has no timeout at all and it can quietly answer a repeated GET from the cache. WinHttpRequest gives the most control and is the one to try when the other two refuse to connect through a particular proxy or certificate setup.
curl tool from a script. Guard Windows-only code with #If Mac Then so a Mac user gets a clear message instead of a cryptic error.A worked example: one exchange rate, start to finish
Imagine a finance team in Zurich that books a handful of euro invoices every day and wants the current CHF to EUR reference rate in cell B1 of its booking sheet. Their rate provider exposes an API. For this article we use the placeholder address https://api.example.com/latest?from=CHF&to=EUR, so the call itself is fictional, and the rate 1.07 is only an example value. The table shows every part of the round trip and the VBA member that sets or reads it.
| Part | In this example | Set or read in VBA with |
|---|---|---|
| Method | GET | http.Open "GET", url, False |
| URL | https://api.example.com/latest?from=CHF&to=EUR | the second argument of .Open |
| Request header | Accept: application/json | http.setRequestHeader "Accept", "application/json" |
| Request header | Cache-Control: no-cache | http.setRequestHeader "Cache-Control", "no-cache" |
| Body | none (GET requests normally have none) | http.send with no argument |
| Status | 200 | http.Status |
| Status text | OK | http.statusText |
| Response header | Content-Type: application/json | http.getResponseHeader("Content-Type") |
| Response body | {"amount":1.0,"base":"CHF","date":"2026-10-30","rates":{"EUR":1.07}} | http.responseText |
Here is the complete macro. It is a slimmed-down version of the one in the lab, with the same structure: timeouts first, then the request, then three separate checks before anything is written to the sheet. Paste it into a standard module (Alt+F11, then Insert > Module). Because the URL is a placeholder it will stop at the first check with a "No reply" message, which is exactly the behaviour you want to see when a host cannot be reached.
Option Explicit
Sub GetRateFromApi()
Const URL As String = "https://api.example.com/latest?from=CHF&to=EUR"
Dim http As Object
Dim body As String
Dim p As Long
Dim rate As Double
Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.setTimeouts 5000, 5000, 10000, 15000
On Error Resume Next
http.Open "GET", URL, False
http.setRequestHeader "Accept", "application/json"
http.setRequestHeader "Cache-Control", "no-cache"
http.send
If Err.Number <> 0 Then
MsgBox "No reply: " & Err.Description, vbExclamation
Exit Sub
End If
On Error GoTo 0
If http.Status <> 200 Then
MsgBox "Status " & http.Status & " " & http.statusText, vbExclamation
Exit Sub
End If
body = http.responseText
p = InStr(1, body, """EUR"":", vbBinaryCompare)
If p = 0 Then
MsgBox "No EUR value in: " & Left$(body, 300), vbExclamation
Exit Sub
End If
rate = Val(Mid$(body, p + Len("""EUR"":")))
ActiveSheet.Range("A1").Value = "1 CHF in EUR"
ActiveSheet.Range("B1").Value = rate
End Sub
After a successful run the sheet holds just two cells, which is deliberate. A macro that writes one clearly labelled value is easy to check, and adding a timestamp next to it, as the lab version does, tells every reader how fresh the number is. The last row of the next table shows how to cross-check the parsing with worksheet formulas: paste the raw JSON into D1 and the formula in C1 must give the same number as the macro.
| Cell | Written by | Example value |
|---|---|---|
| A1 | ws.Range("A1").Value = "1 CHF in EUR" | 1 CHF in EUR |
| B1 | ws.Range("B1").Value = rate | 1.07 (for example) |
| A2 | ws.Range("A2").Value = "Fetched" | Fetched |
| B2 | ws.Range("B2").Value = Now, format yyyy-mm-dd hh:mm | 2026-10-30 09:15 |
| C1 (formula check) | =NUMBERVALUE(TEXTBEFORE(TEXTAFTER(D1,"""EUR"":"),"}"),".") | 1.07, read from the raw text pasted into D1 |
TEXTAFTER and TEXTBEFORE need Excel for Microsoft 365 or Excel 2024. The doubled quotes in """EUR"":" are how a formula writes the text "EUR":, and NUMBERVALUE(...,".") forces the dot to be the decimal separator, which is the same job Val does in VBA. Excel for Windows also has a worksheet function, =WEBSERVICE("https://api.example.com/latest?from=CHF&to=EUR"), that performs a plain GET and returns the body as text. It is handy for a quick look, but it cannot send headers, cannot show you the status code and is not available in Excel for Mac or Excel for the web, which is why serious work moves to VBA.
Reading the macro line by line
setTimeouts 5000, 5000, 10000, 15000sets the limits for name resolution, connecting, sending and receiving, in milliseconds. It must be called before.send..Open "GET", URL, False: the third argument is Async.Falsemakes.sendwait until the response is complete, which is what a report macro wants..setRequestHeadercalls belong between.Openand.send. Called before.Openthey raise an error.On Error Resume Nextaround.sendcatches the case where nothing answers at all.On Error GoTo 0switches normal error handling back on straight afterwards, so later bugs are not hidden.http.Status <> 200is a separate check, because a 404 or 401 is a completed round trip. No VBA error is raised andresponseTextcontains the server's complaint, not your data.InStrplusVal(Mid$(...))finds the marker"EUR":and reads the number after it.Valstops at the first character that is not part of a number and always uses the dot as decimal point.
Three checks before anything touches the sheet
The most important design decision in the macro is that it never writes a number it is not sure about. There are three different ways a call can go wrong, and each one needs its own check because each one looks different from inside VBA.
| What happened | VBA error at .send? | http.Status | What responseText holds |
|---|---|---|---|
| Everything worked | no | 200 | your data |
| Wrong path or ID | no | 404 | an error page or error JSON |
| Missing or wrong API key | no | 401 or 403 | the server's complaint |
| Too many calls too fast | no | 429 | a rate-limit message |
| Server-side failure | no | 500 or 503 | an error page |
| No network, DNS failure, blocked host, timeout | yes | not available | nothing useful |
Notice the last row. When there is no network, the host name cannot be resolved or a timeout fires, .send raises a VBA run-time error and there is no status to read. In every other row the call technically succeeded, the server simply said something you did not want to hear. Mixing these two up is the most common reason a web macro writes an error page into a cell or crashes on a laptop that is offline. The next lessons turn this pattern into a reusable function that returns a clear result for each case.
Timeouts: the difference between a slow reply and a frozen Excel
A synchronous request blocks Excel until it finishes. Without limits, a host that accepts the connection and then never answers can leave Excel unresponsive for a very long time, and the only way out is Task Manager, losing unsaved work. setTimeouts takes four separate limits because each phase fails differently: name resolution fails fast when DNS is broken, connecting fails when a firewall drops packets, and receiving is the phase that legitimately takes longest for a big reply.
The values are a starting point, not a rule. A rates endpoint that returns a few hundred bytes should answer within a second or two, so 15 seconds to receive is generous. An export endpoint that builds a large file may need more. What matters is that some limit exists, and that the macro reports a timeout in plain words rather than leaving the user staring at a spinning cursor.
How to try it in Excel, step by step
- Open a new workbook and save it straight away as Excel Macro-Enabled Workbook (*.xlsm) with File > Save As (
F12). A plain .xlsx cannot keep VBA code. - Press
Alt+F11to open the VBA editor, then Insert > Module to add a standard module. - Type
Option Explicitat the very top if the editor did not add it. It forces every variable to be declared, which catches typos in long macros. - Paste the macro from the lab above (it uses a real, free public endpoint) or the example from this article (placeholder URL).
- Open the Immediate window with
Ctrl+G.Debug.Printoutput appears here, which is where you inspect the raw response. - Click inside the Sub and press
F5to run it, orF8to step through one line at a time and watch the variables in View > Locals Window. - Switch back to Excel with
Alt+F11and check the cells and the message box. Then disconnect from the network and run it again: the macro should report that there was no reply, and the sheet should stay unchanged.
The quickest way to see a reply is a tiny diagnostic macro that prints the status, one header and the first part of the body to the Immediate window. Keep it in your workbook while you develop, because it answers the first question of every debugging session: what did the server actually send?
Sub PeekAtResponse()
Dim http As Object
Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
http.setTimeouts 5000, 5000, 10000, 15000
http.Open "GET", "https://api.example.com/latest?from=CHF&to=EUR", False
http.send
Debug.Print http.Status; " "; http.statusText
Debug.Print http.getResponseHeader("Content-Type")
Debug.Print Left$(http.responseText, 500)
End Sub

Common mistakes and how to spot them
- Treating any reply as success. Symptom: an HTML error page or text like Unauthorized appears in a cell. Fix: check
http.Statusbefore you read the body. - No timeouts. Symptom: Excel shows "Not Responding" when the server is slow and only Task Manager helps. Fix: use
ServerXMLHTTPorWinHttpRequestand callsetTimeoutsbefore.send. - Stale answers from plain XMLHTTP. Symptom: the server data changed but the macro keeps showing the old value. Fix: switch to
ServerXMLHTTP, sendCache-Control: no-cache, or append a changing dummy parameter to the URL. - Using CDbl on the reply. Symptom: 1.07 turns into 107 or a type mismatch on a machine with a comma as decimal separator. Fix: read JSON numbers with
Val, which always expects a dot. - Leaving On Error Resume Next switched on. Symptom: later bugs vanish silently and the sheet gets zeros. Fix: follow the risky line with an
Err.Numbercheck and thenOn Error GoTo 0. - Putting a secret in the URL. Symptom: an API key shows up in proxy logs, browser history or a screenshot. Fix: send keys in a header, as later lessons show, and keep them out of the workbook you share.
- Saving as .xlsx. Symptom: the macro is gone after reopening. Fix: save as .xlsm.
Quick reference
| Item | What it does |
|---|---|
CreateObject("MSXML2.ServerXMLHTTP.6.0") | creates the HTTP object (Windows only), no reference needed |
.setTimeouts r, c, s, rcv | resolve, connect, send and receive limits in milliseconds |
.Open "GET", url, False | prepares a synchronous request, False = wait for the answer |
.setRequestHeader name, value | adds a header, must come after .Open and before .send |
.send / .send body | sends the request, with an optional body for POST |
.Status, .statusText | the HTTP status number and its short text |
.responseText | the body as a string |
.getResponseHeader("Content-Type") | reads one response header |
Val(text) | reads a number with . as decimal point on every locale |
=WEBSERVICE(url) | worksheet function, Excel for Windows, returns the body of a GET |
=TEXTAFTER, =TEXTBEFORE, =NUMBERVALUE | cut a value out of text and convert it with a fixed decimal separator |
Alt+F11, Ctrl+G, F5, F8 | VBA editor, Immediate window, run, step line by line |
Real-world uses
- Daily rates in a booking sheet. A finance team pulls the reference rate for each currency it books and stamps the fetch time next to it, so the auditor can see which rate was used.
- Stock levels from a shop system. A buyer refreshes on-hand quantities for 50 SKUs from the shop's API every morning instead of exporting a CSV and pasting it in.
- Ticket counts for a support dashboard. A team lead fetches open, overdue and closed tickets per queue and feeds them into a chart that updates with one button.
- Status checks for a list of shipments. A logistics planner loops over tracking numbers, calls the carrier's API for each one, and writes the latest status, pausing between calls to respect the rate limit.
What you will build in the rest of this course
Lesson 1 is free. The seven lessons below are part of the paid course, a one-time purchase of $9.90, and each one builds on the macro you have just read.
Your First GET Request. You write a GET call from scratch in five lines, learn why the order of .Open, headers and .send matters, and build query strings with proper URL encoding so that spaces, ampersands and accented characters do not break the request.
Status Codes and Handling Failure. You meet the status numbers that actually turn up in practice, learn why status 0 is a special case, read the error body the server sends, and wrap everything in a function that reports success or failure cleanly to the code that calls it.
Headers, POST and API Keys. You send an API key in a header instead of the URL, post a JSON body and a form-encoded body, build JSON text safely so a quote in a customer name cannot break it, and decide where a key should live so that it never ends up in a shared workbook.
JSON in VBA: an Honest Assessment. VBA has no JSON parser. This lesson compares the options people use, including the ScriptControl and htmlfile tricks and the open-source VBA-JSON module, and explains which ones still work in 64-bit Office and which one is the practical answer.
Simple Parsing Without a Library. For small, predictable replies you pull out text and number values with string functions, chop an array of objects into rows, see exactly where this approach breaks, and make the code fail loudly instead of guessing.
Timeouts, Retries and Rate Limits. You choose timeout values deliberately, retry only the failures worth retrying, wait the right amount after a 429, and keep the user informed in the status bar during a long run.
Putting the Results on a Sheet. You put the whole job together, from request to a formatted table, write values in one block instead of cell by cell, make sure dates and numbers land with the right types, and turn the result into something a colleague can refresh with one click.
Summary
A web call from VBA is one request and one response, handled by a Windows COM object. Pick MSXML2.ServerXMLHTTP.6.0 for unattended macros, set timeouts before you send, and check three things separately: did .send raise an error, is the status 200, and is the value you expect actually in the body. Read numbers with Val so the decimal point survives every locale, and write to the sheet only when all three checks pass. Now scroll up, run the macro in the lab, then switch off your network and run it again to see the failure path for yourself, and finish with the quick check question.
Frequently asked questions
Can Excel VBA call a REST API?
Yes. On Windows, VBA can create the MSXML2.ServerXMLHTTP or WinHttp.WinHttpRequest COM object with CreateObject, send GET or POST requests and read the status and response body. No add-in or reference is required.
Which is better in VBA, XMLHTTP or ServerXMLHTTP?
For macros that run unattended, MSXML2.ServerXMLHTTP.6.0 is usually the better choice because it supports setTimeouts and does not serve repeated requests from the Windows cache. Plain XMLHTTP is simpler and reuses the user's proxy settings, but has no timeout control.
Does VBA web code work on Excel for Mac?
Not with these objects. MSXML and WinHTTP are Windows components, so Mac workbooks typically call the system curl tool from a script instead. Guard Windows-only code with #If Mac Then.
Why does my VBA HTTP request return old data?
Plain MSXML2.XMLHTTP goes through the WinINET cache, so a repeated GET can be answered from disk. Switch to ServerXMLHTTP, send a Cache-Control: no-cache header, or add a changing dummy parameter to the URL.
How do I stop Excel freezing when a web request hangs?
Call setTimeouts on ServerXMLHTTP or SetTimeouts on WinHttpRequest before .send, for example 5000, 5000, 10000, 15000 milliseconds. When a limit is reached .send raises an error that your macro can catch and report.
Can Excel read JSON from a web API without VBA?
Excel for Windows has the WEBSERVICE function for simple GET requests, and Power Query can import and parse JSON. VBA is the better fit when you need headers, status checks, error messages or full control over where the data lands.
Keep going: Web, APIs & JSON
This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time CHF 9.90.
- Your First GET Request
- Status Codes and Handling Failure
- Headers, POST and API Keys
- JSON in VBA: an Honest Assessment
- Simple Parsing Without a Library
- Timeouts, Retries and Rate Limits
- Putting the Results on a Sheet