Tabellab

How VBA Talks to the Web

Lesson 1 of 8Reading

A request and a response, nothing more

Every web call has the same shape. You send a request: a method (GET, POST), a URL, some headers, sometimes a body. The server sends back a response: a status number, some headers, and a body of text. VBA has no Http keyword. Instead you create a Windows COM object that does the talking and read the answer out of its properties. Say the platform part plainly: these objects exist on Windows only. Excel for Mac has no supported HTTP object, and the usual workaround there is shelling out to curl.

Three objects, and which to pick

  • MSXML2.XMLHTTP - simplest. It rides on the machine's Internet Explorer stack, inheriting proxy settings, cookies and credentials. Convenient behind a corporate proxy, but it has no timeout control, and it caches.
  • MSXML2.ServerXMLHTTP.6.0 - the same interface plus a real setTimeouts and its own network stack. The sensible default for unattended code, and what the macro below uses.
  • WinHttp.WinHttpRequest.5.1 - the most control: timeouts, proxy, redirect and certificate options. Reach for it when the other two misbehave.
Option Explicit

Sub WhichObjects()
    Dim a As Object
    Dim b As Object
    Dim c As Object

    Set a = CreateObject("MSXML2.XMLHTTP")               ' simple, no timeouts
    Set b = CreateObject("MSXML2.ServerXMLHTTP.6.0")     ' the sensible default
    Set c = CreateObject("WinHttp.WinHttpRequest.5.1")   ' the most control

    Debug.Print TypeName(a); " "; TypeName(b); " "; TypeName(c)
End Sub

A complete call you can run right now

This fetches today's CHF-to-EUR reference rate from frankfurter.app, a free public service that publishes European Central Bank rates. No key, no account, no sign-up. Paste it into a standard module (Alt+F11, Insert - Module) and press F5 in GetReferenceRate. With no network it tells you so and stops; it does not crash and it does not write a wrong number to the sheet.

Option Explicit

Sub GetReferenceRate()
    Dim http As Object
    Dim url As String
    Dim body As String
    Dim rate As Double
    Dim ws As Worksheet

#If Mac Then
    MsgBox "The HTTP objects used here are Windows components. " & _
           "Excel for Mac has no supported equivalent.", vbExclamation
    Exit Sub
#End If

    ' A public endpoint: European Central Bank rates, no key, no sign-up
    url = "https://api.frankfurter.app/latest?from=CHF&to=EUR"

    Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")

    On Error Resume Next
    http.setTimeouts 5000, 5000, 10000, 15000
    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 at all." & vbCrLf & _
               "VBA error " & Err.Number & ": " & Err.Description & vbCrLf & vbCrLf & _
               "No connection, a proxy in the way, or the host is blocked. " & _
               "This is a network problem, not a fault in the code.", _
               vbExclamation, "Request failed"
        Err.Clear
        Exit Sub
    End If
    On Error GoTo 0

    If http.Status <> 200 Then
        MsgBox "The server answered, but with status " & http.Status & " " & _
               http.statusText & ", so there is no rate to read.", _
               vbExclamation, "Unexpected status"
        Exit Sub
    End If

    body = http.responseText
    rate = NumberAfter(body, """EUR"":")

    If rate = 0 Then
        MsgBox "A reply arrived but held no EUR rate. First 300 characters:" & _
               vbCrLf & vbCrLf & Left$(body, 300), vbExclamation
        Exit Sub
    End If

    Set ws = DemoSheet("WebDemo")
    ws.Range("A1").Value = "1 CHF in EUR"
    ws.Range("B1").Value = rate
    ws.Range("A2").Value = "Fetched"
    ws.Range("B2").Value = Now
    ws.Range("B2").NumberFormat = "yyyy-mm-dd hh:mm"
    ws.Columns("A:B").AutoFit
    ws.Activate

    Debug.Print body

    MsgBox "1 CHF = " & rate & " EUR", vbInformation, "Done"
End Sub

Private Function NumberAfter(ByVal jsonText As String, ByVal marker As String) As Double
    Dim p As Long

    p = InStr(1, jsonText, marker, vbBinaryCompare)
    If p = 0 Then Exit Function

    ' Val stops at the first character that is not part of a number,
    ' and always reads "." as the decimal point, on every locale
    NumberAfter = Val(Mid$(jsonText, p + Len(marker)))
End Function

Private Function DemoSheet(ByVal sheetName As String) As Worksheet
    Dim ws As Worksheet

    On Error Resume Next
    Set ws = ThisWorkbook.Worksheets(sheetName)
    On Error GoTo 0

    If ws Is Nothing Then
        Set ws = ThisWorkbook.Worksheets.Add( _
            After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
        ws.Name = sheetName
    End If

    Set DemoSheet = ws
End Function

Reading it line by line

  • setTimeouts 5000, 5000, 10000, 15000 - resolve, connect, send and receive, in milliseconds. Without them a dead host leaves Excel frozen with no way out but Task Manager.
  • The False in .Open is the Async argument. It makes .send wait for the answer, which is what a report macro wants; asynchronous calls in VBA mean polling readyState in a DoEvents loop.
  • On Error Resume Next around .send catches the offline case: when nothing answers, .send raises a VBA error, so the macro checks Err.Number, says so in words and exits.
  • http.Status is checked separately, because a 404 or a 401 is still a completed round trip: no VBA error is raised and responseText contains the server's complaint instead of your data.
  • NumberAfter is deliberately crude: it finds "EUR": and reads what follows. It uses Val, not CDbl, because Val always treats . as the decimal point - otherwise the rate becomes 106 on a German machine.
  • The rate = 0 check covers a reply in an unexpected shape: you see the first 300 characters instead of a silent zero on the sheet.

The trap: you are being served yesterday's answer

MSXML2.XMLHTTP goes through Windows' WinINET cache. Call the same URL twice and the second call may be answered from disk without touching the network. You fix the server, re-run the macro, see the old value, and spend an hour debugging code that was already correct. ServerXMLHTTP has its own stack and does not do this, but a proxy in between still can. Two cheap defences:

' Belt and braces against a cached answer
http.setRequestHeader "Cache-Control", "no-cache"
http.setRequestHeader "Pragma", "no-cache"

' Or make every URL unique, which no cache can match
url = url & "&_=" & CLng(Timer * 1000)
Get the call working in a browser or in Postman before writing any VBA. Once you know the URL, the headers and the shape of the reply, the macro is only transcription - and if it fails, the fault is yours, not the endpoint's.

How it goes on

The pattern above is a start, not a finished tool. The next lessons build a GET wrapper that reports failure properly, work through the status codes you will meet, and cover headers, POST bodies and where an API key belongs - a header, never the URL. Then comes an honest assessment of JSON in VBA, which has no built-in parser at all, followed by retries, rate limits and whole result sets on a sheet.

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.

One web call = one request + one responseYour macroVBA, Excelfor WindowsCOM objectMSXML2.ServerXMLHTTPWeb serverapi.example.com(placeholder).sendrequestresponse.StatusRequestGET /latest?from=CHF&to=EURHost: api.example.comAccept: application/jsonResponseStatus 200, statusText OKContent-Type: application/jsonBody: {"rates":{"EUR":1.07}}
The macro never talks to the server directly. It fills in a request on a COM object, sends it, and reads the status and body back. The host name is a placeholder.

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.XMLHTTPMSXML2.ServerXMLHTTP.6.0WinHttp.WinHttpRequest.5.1
Timeout controlnonesetTimeouts (four values in ms)SetTimeouts (four values in ms)
Network stackWinINET (the old Internet Explorer stack)WinHTTPWinHTTP
Caches GET repliesyes, can serve a stale answerno own cacheno own cache
Uses the user's proxy and sign-in automaticallyyesnot by defaultconfigurable
Good forquick tests on an office PCunattended 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.

All three are Windows components. Excel for Mac has no supported equivalent, so a workbook that must also run on a Mac needs a different route, usually calling the system 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.

PartIn this exampleSet or read in VBA with
MethodGEThttp.Open "GET", url, False
URLhttps://api.example.com/latest?from=CHF&to=EURthe second argument of .Open
Request headerAccept: application/jsonhttp.setRequestHeader "Accept", "application/json"
Request headerCache-Control: no-cachehttp.setRequestHeader "Cache-Control", "no-cache"
Bodynone (GET requests normally have none)http.send with no argument
Status200http.Status
Status textOKhttp.statusText
Response headerContent-Type: application/jsonhttp.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.

CellWritten byExample value
A1ws.Range("A1").Value = "1 CHF in EUR"1 CHF in EUR
B1ws.Range("B1").Value = rate1.07 (for example)
A2ws.Range("A2").Value = "Fetched"Fetched
B2ws.Range("B2").Value = Now, format yyyy-mm-dd hh:mm2026-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, 15000 sets 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. False makes .send wait until the response is complete, which is what a report macro wants.
  • .setRequestHeader calls belong between .Open and .send. Called before .Open they raise an error.
  • On Error Resume Next around .send catches the case where nothing answers at all. On Error GoTo 0 switches normal error handling back on straight afterwards, so later bugs are not hidden.
  • http.Status <> 200 is a separate check, because a 404 or 401 is a completed round trip. No VBA error is raised and responseText contains the server's complaint, not your data.
  • InStr plus Val(Mid$(...)) finds the marker "EUR": and reads the number after it. Val stops 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.

Three checks before anything touches the sheet.sendthe requestVBA errorraised?Status= 200?Valuefound?Write tothe sheetnoyesyesyesNetwork problemsay so, exitnoServer said noshow status, exitnoWrong shapeshow 300 charsOnly the green path writes a number. Every other path explains itself and stops.
The decision path of the macro. A VBA error means the network failed, a status other than 200 means the server refused, and a missing marker means the reply had an unexpected shape.

What happenedVBA error at .send?http.StatusWhat responseText holds
Everything workedno200your data
Wrong path or IDno404an error page or error JSON
Missing or wrong API keyno401 or 403the server's complaint
Too many calls too fastno429a rate-limit message
Server-side failureno500 or 503an error page
No network, DNS failure, blocked host, timeoutyesnot availablenothing 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.

http.setTimeouts 5000, 5000, 10000, 15000Limit in seconds0 s4 s8 s12 s16 sResolve (DNS)5 sConnect5 sSend10 sReceive15 s
The four limits used in the lab, converted to seconds. In the worst case the macro gives up after these limits instead of hanging Excel. Choose your own values for the API you call.

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

  1. 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.
  2. Press Alt+F11 to open the VBA editor, then Insert > Module to add a standard module.
  3. Type Option Explicit at the very top if the editor did not add it. It forces every variable to be declared, which catches typos in long macros.
  4. Paste the macro from the lab above (it uses a real, free public endpoint) or the example from this article (placeholder URL).
  5. Open the Immediate window with Ctrl+G. Debug.Print output appears here, which is where you inspect the raw response.
  6. Click inside the Sub and press F5 to run it, or F8 to step through one line at a time and watch the variables in View > Locals Window.
  7. Switch back to Excel with Alt+F11 and 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.
Before you write any VBA for a new API, make the call work in a browser or an API tool first. Once you know the exact URL, the headers it needs and what the reply looks like, the macro is just transcription, and if the macro fails you know the problem is in your code, not in the endpoint.

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

Excel VBA editor next to a worksheet that receives data from a web API as JSON
Web, APIs and JSON in VBA: the macro asks a web service for data and puts the answer on a sheet.

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.Status before you read the body.
  • No timeouts. Symptom: Excel shows "Not Responding" when the server is slow and only Task Manager helps. Fix: use ServerXMLHTTP or WinHttpRequest and call setTimeouts before .send.
  • Stale answers from plain XMLHTTP. Symptom: the server data changed but the macro keeps showing the old value. Fix: switch to ServerXMLHTTP, send Cache-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.Number check and then On 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

ItemWhat it does
CreateObject("MSXML2.ServerXMLHTTP.6.0")creates the HTTP object (Windows only), no reference needed
.setTimeouts r, c, s, rcvresolve, connect, send and receive limits in milliseconds
.Open "GET", url, Falseprepares a synchronous request, False = wait for the answer
.setRequestHeader name, valueadds a header, must come after .Open and before .send
.send / .send bodysends the request, with an optional body for POST
.Status, .statusTextthe HTTP status number and its short text
.responseTextthe 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, =NUMBERVALUEcut a value out of text and convert it with a fixed decimal separator
Alt+F11, Ctrl+G, F5, F8VBA 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 โ‚ฌ9.90.

  1. Your First GET Request
  2. Status Codes and Handling Failure
  3. Headers, POST and API Keys
  4. JSON in VBA: an Honest Assessment
  5. Simple Parsing Without a Library
  6. Timeouts, Retries and Rate Limits
  7. Putting the Results on a Sheet

Buy course โ€” โ‚ฌ9.90 See the full course

Knowledge check

Your macro calls the same URL twice and gets the identical old answer, although the data on the server has changed. What is the most likely cause?

Continues in this course
  • 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

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course โ€” โ‚ฌ9.90