To call a REST API from an Excel macro, you use the Microsoft XML, v6.0 (MSXML) library within the Visual Basic for Applications (VBA) editor to send an HTTP request and receive a response. This process allows you to automate data retrieval from web services—such as currency converters, weather services, or internal company databases—and populate your spreadsheets in real-time without manual data entry.

What You'll Need

  • Microsoft Excel installed on a Windows PC (VBA for REST APIs is not supported in Excel for the Web).
  • The API endpoint URL you wish to call.
  • An API key or authentication token if the service is not public.
  • Developer tab enabled in the Excel Ribbon.
  • Administrative rights to enable specific object libraries in the VBA editor.

Step-by-Step

  1. Enable the Developer Tab: Right-click any existing tab on the Excel Ribbon and select Customize the Ribbon. In the right-hand column, check the box for Developer and click OK. This provides access to the Visual Basic editor.
  2. Open the VBA Editor: Click the Developer tab and select Visual Basic, or press Alt + F11 on your keyboard.
  3. Insert a New Module: In the Project Explorer on the left, right-click your workbook name, hover over Insert, and select Module. This creates a clean space to write your code, separate from sheet-specific logic.
  4. Add the Necessary Reference: To use the HTTP request tools, you must tell VBA which library to use. Go to the Tools menu at the top, select References, scroll down until you find Microsoft XML, v6.0, check the box next to it, and click OK. If you do not do this, the code will throw a "User-defined type not defined" error.
  5. Define the API Request Variables: Start your macro by declaring the objects needed to handle the connection. You will need an MSXML2.XMLHTTP60 object to send the request and a string variable to hold the URL and the response text.
  6. Configure the Request Method: Determine if you are using a GET request (to retrieve data) or a POST request (to send data). For a GET request, use .Open "GET", url, False. The "False" parameter tells Excel to wait for the server to respond before moving to the next line of code (synchronous request).
  7. Set Request Headers: If the API requires specific formats, such as JSON, you must set the headers. Use .setRequestHeader "Content-Type", "application/json". If the API requires an API key, you often add it here as well, such as .setRequestHeader "Authorization", "Bearer YOUR_TOKEN_HERE".
  8. Send the Request: Use the .send method. For GET requests, this is usually empty: .send. For POST requests, you would pass the data body inside the parentheses.
  9. Capture the Response: Once the request is sent, the server returns a status code. Check that the status is 200 (which means "OK") using If oHttp.Status = 200 Then. If successful, capture the response using responseString = oHttp.responseText.
  10. Parse the Data into Cells: Since most APIs return data in JSON format, you will need to extract the specific values you want. While VBA does not have a built-in JSON parser, for simple responses, you can use the Split() function or InStr() to find specific keys and values. For complex JSON, you may need to import a third-party VBA-JSON library.
  11. Output to Sheet: Assign the extracted value to a cell using Range("A1").Value = extractedValue.

Common Mistakes

One of the most frequent errors is forgetting to enable the Microsoft XML, v6.0 reference in the Tools menu. Without this, VBA cannot recognize the XMLHTTP object. Another common mistake is hard-coding API keys directly into the script. If you share the workbook, anyone with access to the VBA editor can see your private keys. It is better to store the key in a hidden cell and reference that cell in your code.

Users also frequently confuse GET and POST requests. Using a GET request when the API expects a POST (or vice versa) will usually result in a 405 Method Not Allowed error. Additionally, failing to handle the response as a string can lead to crashes if the API returns an unexpected error message instead of the expected data payload. Always wrap your request in a check for the HTTP status code before attempting to parse the response.

Tips

To make your macro more robust, use a "Try-Catch" style approach by using On Error GoTo ErrorHandler at the start of your sub. This prevents Excel from freezing or crashing if the internet connection drops or the API server is down. Instead of a crash, you can display a user-friendly message box saying "Server unavailable, please try again later."

For better performance, avoid calling the API inside a loop that runs hundreds of times. Every single API call creates a new network request, which can slow down your workbook and may lead to the API provider blocking your IP address for making too many requests (rate limiting). If possible, request a larger batch of data in one call and then distribute that data across your cells using VBA.

If you are dealing with very large JSON responses, consider using a dedicated JSON parser for VBA. This allows you to treat the API response as a dictionary or a collection, making it much easier to access nested data without writing complex string manipulation logic.

Troubleshooting

If the macro does not execute, first check your internet connection and verify that the API URL is correct by pasting it directly into a web browser. If the browser returns the data but Excel does not, check the References menu again to ensure Microsoft XML, v6.0 is checked.

If you receive a 401 Unauthorized error, your API key is either missing, expired, or incorrectly formatted in the request header. Double-check whether the API expects the key in the header or as a query parameter in the URL (e.g., ?api_key=123). A 403 Forbidden error usually means you have the right key, but your account does not have permission to access that specific data endpoint.

If the response is returned but looks like a long string of text in a single cell, you have successfully called the API but have not yet parsed the JSON. You will need to use string functions to isolate the data you need. If Excel freezes entirely during the call, ensure you are using a synchronous call (False) for simple scripts, but be aware that if the server takes too long to respond, Excel will appear unresponsive until the timeout is reached.

Frequently Asked Questions

Can I use this on a Mac?

No, the MSXML library is a Windows-specific component. Mac users must use different methods, such as the curl command via the VBA Shell function, to interact with REST APIs.

Do I need to pay for an API to do this?

It depends on the service. Many APIs offer a "Free Tier" for a limited number of requests per day, while others are entirely open and free. Always check the provider's pricing page.

How do I handle JSON data in VBA?

For simple data, use Split() and Replace() to strip away brackets and quotes. For complex, nested JSON, it is highly recommended to download a VBA-JSON parser library from a reputable source like GitHub.

Will this work with HTTPS?

Yes, the Microsoft XML, v6.0 library fully supports HTTPS and handles the encryption and SSL handshakes automatically.

What is the difference between a GET and POST request?

A GET request is used to retrieve data from a server (like reading a page), while a POST request is used to send data to a server (like submitting a form).

Can I schedule the macro to run automatically?

Yes, you can use the Application.OnTime method in VBA to trigger the API call at specific intervals, such as every hour, to keep your data fresh.