How to Calculate Distance in Excel Using Google Maps: The Ultimate Guide


How to Calculate Distance in Excel Using Google Maps: The Ultimate Guide

Instantly generate the VBA code needed to automate distance and travel time calculations directly within your spreadsheets. Perfect for logistics, sales planning, and expense reporting.

Excel Distance VBA Code Generator



You need a Google Cloud Platform account with the ‘Directions API’ and ‘Geocoding API’ enabled. Get an API Key here.

API Key cannot be empty.



The Excel cell containing the starting address (e.g., A2).


The Excel cell containing the destination address (e.g., B2).


Choose the unit for the distance output.

Your Ready-to-Use Excel VBA Code

Copy this code, open the VBA Editor in Excel (Alt + F11), insert a new Module, and paste it in.

How to Use in Excel

Distance Formula:

After pasting the code, use this formula in any cell: =GetDistance(A2, B2)

Travel Time Formula:

Use this formula to get the estimated travel time: =GetTravelTime(A2, B2)

Required References:

In the VBA Editor, go to ‘Tools’ -> ‘References’ and make sure ‘Microsoft XML, v6.0’ and ‘Microsoft Scripting Runtime’ are checked.

What is Calculating Distance in Excel?

Traditionally, finding the driving distance between two points requires manually using an application like Google Maps. When you have dozens or thousands of routes to analyze, this is incredibly inefficient. The technique to how to calculate distance in excel using google maps involves using Excel’s built-in programming language, Visual Basic for Applications (VBA), to communicate directly with the Google Maps API. This allows you to create custom functions, like =GetDistance(), that dynamically fetch real-world travel data for any addresses listed in your spreadsheet.

This method is invaluable for logistics planners, sales managers, real estate analysts, and anyone needing to perform bulk distance calculations for routing, expense reports, or market analysis. Instead of manual data entry, you can automate the entire process, saving countless hours and reducing errors.

A common misconception is that Excel has a native function for this. It does not. The process relies entirely on a custom script that calls an external web service. Another point of confusion is between straight-line distance (which can be calculated with complex trigonometry if you have GPS coordinates) and actual driving distance, which accounts for roads, turns, and traffic conditions. Our method calculates the far more useful driving distance.

The VBA Formula and Technical Explanation

The core of this solution is a VBA script that performs several key steps. It constructs a specific URL, sends an HTTP request to the Google Directions API, receives the data back in a format called JSON, and then parses that data to extract the exact distance and time values. This is a powerful example of how to calculate distance in excel using google maps through automation.

Let’s break down the VBA code our generator creates:

  1. Function Definition: We define public functions like GetDistance(origin As String, destination As String) that can be called from any Excel cell.
  2. URL Encoding: Addresses can contain spaces and special characters. The script first encodes the origin and destination addresses to be URL-safe.
  3. API Request URL Construction: It builds the full API request URL, including the origin, destination, your unique API key, and the desired unit system.
  4. HTTP Request: Using the `MSXML2.ServerXMLHTTP` object, the VBA code sends a GET request to the Google Maps server, essentially asking it for directions.
  5. JSON Parsing: The API returns a detailed JSON object. The script needs to navigate this structured text to find the relevant information. It looks for `routes` -> `legs` -> `distance` -> `value` (for meters) and `routes` -> `legs` -> `duration` -> `value` (for seconds).
  6. Value Conversion & Return: The raw distance is returned in meters and time in seconds. The script converts these values into your chosen units (kilometers/miles and formatted time) before displaying the result in your Excel cell.
VBA Code Key Variables
Variable Meaning Unit Typical Value
origin The starting address passed from the Excel cell. Text “1600 Amphitheatre Parkway, Mountain View, CA”
destination The ending address passed from the Excel cell. Text “1 Infinite Loop, Cupertino, CA”
apiKey Your private key for authenticating with Google’s API. Text “AIzaSy… (a long string of characters)”
serviceUrl The base endpoint for the Google Directions API. URL “https://maps.googleapis.com/maps/api/directions/json?…”
httpReq The object used to make the web request. Object (MSXML2.ServerXMLHTTP.6.0)
JSON The text response from the API containing all route data. JSON Text A structured object with route, leg, and step details.
Data Flow for Excel to Google Maps Distance Calculation

Excel Cell 1. Input

VBA Function 2. Process

3. API Request

Google Maps API (Server) External

4. JSON Response

Excel Cell 5. Output

A visual representation of the data flow when you how to calculate distance in excel using google maps.

Practical Examples

Example 1: Logistics Planning for a Distributor

A beverage distributor in Chicago needs to calculate delivery routes from their warehouse to 50 different stores. Manually checking each route is impossible. By listing all store addresses in Column B and their warehouse address in Column A, they can use the custom function to instantly populate the distance for every single route.

  • Input (Row 2): Origin: “123 Distribution St, Chicago, IL”, Destination: “456 Retail Ave, Naperville, IL”
  • Excel Formula (Cell C2): =GetDistance(A2, B2)
  • Output (Cell C2): 30.5 (miles)
  • Financial Interpretation: The company can now multiply this mileage by their cost-per-mile to accurately forecast fuel and driver costs for their entire delivery network, optimizing routes and budgets. This is a direct application of the vba google maps api integration.

Example 2: Sales Team Expense Reporting

A regional sales manager needs to verify the mileage claims for her team of 15 representatives. Each rep submits a list of client visits. The manager can create a spreadsheet with the start and end points for each trip and use the formula to get the official Google Maps distance, ensuring fair and accurate reimbursement.

  • Input (Row 5): Origin: “789 Corporate Dr, Boston, MA”, Destination: “101 Client Way, Providence, RI”
  • Excel Formula (Cell C5): =GetDistance(A5, B5)
  • Output (Cell C5): 51.2 (miles)
  • Financial Interpretation: At the federal reimbursement rate of $0.67 per mile (as of 2024), this trip would be reimbursed for $34.30. The manager can quickly validate hundreds of claims, saving time and preventing fraudulent submissions. For more details on business calculations, see our mileage reimbursement calculator.

How to Use This VBA Code Generator

Our tool simplifies the process of how to calculate distance in excel using google maps. Follow these steps:

  1. Get Your API Key: You must have a valid Google Maps API key. Our generator links to Google’s official documentation for this. Paste your key into the “Google Maps API Key” field.
  2. Define Your Cells: Enter the cell references for your start and end locations. The defaults are A2 and B2, which is common for row-by-row calculations.
  3. Select Units: Choose whether you want the output in miles or kilometers.
  4. Generate & Copy Code: The tool instantly writes the full VBA code into the text area. Click the “Copy VBA Code” button.
  5. Paste in Excel: Open Excel, press ALT + F11 to open the VBA editor. Go to Insert > Module. Paste the copied code into the new module window.
  6. Enable References: In the VBA Editor, go to Tools > References and check the boxes for ‘Microsoft XML, v6.0’ and ‘Microsoft Scripting Runtime’. This is a critical step.
  7. Use the Formula: Close the VBA editor. Now you can use =GetDistance(A2, B2) and =GetTravelTime(A2, B2) just like any other Excel formula. Drag the fill handle down to apply it to all your rows.

Key Factors That Affect Distance Results

The results from the Google Maps API are highly accurate but can be influenced by several factors. Understanding these is key to mastering how to calculate distance in excel using google maps.

  • API Key Status: A disabled, expired, or incorrectly configured API key is the most common reason for errors. Ensure your key is active and has the necessary APIs enabled in the Google Cloud Console. For help, review our Google API key guide.
  • Address Ambiguity: “Springfield” exists in many states. For best results, use full, unambiguous addresses including street, city, state, and zip code. The API is good at guessing, but precision removes all doubt.
  • API Usage Limits & Cost: The Google Maps API is a paid service. While there is a generous free tier, high-volume usage (thousands of calculations per day) can incur costs. Monitor your usage in the Google Cloud dashboard to avoid unexpected bills.
  • Travel Mode: The current script defaults to ‘driving’. The API can also calculate distances for walking, bicycling, and transit, which would require a small modification to the VBA code to change the `mode` parameter.
  • Real-Time vs. Typical Traffic: By default, the Directions API provides a travel time based on typical traffic conditions. For real-time data, the API call can be modified, though this may impact costs and complexity.
  • VBA Environment Setup: For the script to work, the correct “References” (Microsoft XML and Scripting Runtime) must be enabled in Excel’s VBA editor. Forgetting this step will cause compilation errors. Our advanced VBA techniques article covers this in more detail.

Frequently Asked Questions (FAQ)

Is a Google Maps API key free?
Google provides a recurring monthly credit for Maps API usage, which makes it free for low-to-moderate use cases. High-volume users will need to set up a billing account.
Why am I getting a #NAME? error in Excel?
This error means Excel doesn’t recognize the function name. It almost always indicates that the VBA code was not pasted correctly into a standard Module, or that macros are disabled in your Excel settings.
Why am I getting a #VALUE! error?
This error typically means the VBA function ran but couldn’t get a valid result. The most common causes are an invalid API key, no internet connection, or an address that Google Maps could not find. Check your API key and address formatting first.
Can this tool calculate distance for a list of 10,000 addresses?
Yes, but be cautious. Running 10,000 requests can take a significant amount of time and will likely exceed the free usage tier, resulting in charges to your Google Cloud account.
Can I calculate the distance between three or more points?
Yes, but it requires modifying the VBA. The Google Maps API supports waypoints. You would need to adapt the function to accept an array or range of cells and loop through them to build the request URL. This is a feature of the more advanced route optimization calculator.
How often is the distance data updated?
The distance is based on Google’s current road network data. Travel time can fluctuate based on traffic, but the physical distance of a route rarely changes unless a new road is built.
Does this work on Mac?
Yes, the VBA code is compatible with Excel for Mac, but the process to open the VBA editor and enable references might have slightly different menu paths. The core functionality remains the same.
Can I share the Excel file with others?
Yes, but they will need to enable macros to use the functions. Also, be aware that your API key is stored in the VBA code. If the key is sensitive, you may want to have each user insert their own.

Related Tools and Internal Resources

If you found this guide on how to calculate distance in excel using google maps useful, you may also be interested in these related tools and articles:

  • Bulk Address Geocoder: Convert a list of street addresses into precise latitude and longitude coordinates, another powerful feature of the Google Maps API.
  • Mileage Reimbursement Calculator: A simple tool for calculating expense reimbursements based on distance and official rates.
  • Comprehensive Google API Key Guide: A step-by-step walkthrough on setting up your Google Cloud account and generating the API keys you need for this and other projects.
  • Excel Data Cleaning Tips: Poorly formatted addresses can break the API. Learn how to clean and standardize your data for reliable results.
  • Route Optimization Calculator: For more complex logistics involving multiple stops, this tool helps find the most efficient path.
  • Advanced Excel VBA Techniques: Dive deeper into what’s possible with VBA, from automating reports to building custom applications within Excel.

© 2026 Your Website. All Rights Reserved. This tool is for informational purposes only. Always verify critical data.


Leave a Reply

Your email address will not be published. Required fields are marked *