google maps distance

Excel VBA Calculate distance between two addresses or coordinates

1 Star2 Stars3 Stars4 Stars5 Stars (22 votes, average: 4.55 out of 5)

Ever wanted to calculate the distance between two addresses in Excel? I recently had the following issue: from a list of over approx. 50 administration offices across my city I wanted to find the one that is closest to my workplace. Of course open Google Maps and type each location one by one… and then choose the shortest connection. By why bother when we have Google Maps Distance Matrix API!!!

This post includes information on how to calculate the distance in Excel:

To get the COORDINATES of any ADDRESS read this post

Using the Google Maps Distance Matrix API

Google has a lot of useful API out there and I encourage you to go sometime to the Google API Explorer and have a look at what other information you can easily utilize from Excel or your other applications.

Let’s however focus on getting the distance between two addresses. Google facilitates Google Maps Distance Matrix API for limited usage.

The API is configured using GET HTTP Params. A simple example below.
Say we want to get the distance between San Francisco and Victoria BC. We want to get there by bicycle. Copy this link into your browser:|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=en
Google Distance between Vancouver, BC, Canada and San Francisco, CA, USA
Google Distance between Vancouver, BC, Canada and San Francisco, CA, USA

Google Distance Matrix Builder

Want to quickly test the Google API? Below a simple form for building a quick Distance URL. Simply type in the From an To addresses, select the transportation mode and hit Build URL!. Go here for more options for configuring the Google Maps Distance Matrix API.


Google Maps Distance Matrix URL:

Calculate distance between two addresses using Google Maps in Excel

So I knocked up quickly this VBA Function in Excel which uses Google API distance matrix function to calculate the Google Maps distance. See the VBA code here:

Get Google Maps distance in meters

'Calculate Google Maps distance between two addresses
Public Function GetDistance(start As String, dest As String)
    Dim firstVal As String, secondVal As String, lastVal As String
    firstVal = ""
    secondVal = "&destinations="
    lastVal = "&mode=car&language=pl&sensor=false"
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
    objHTTP.Open "GET", URL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    GetDistance = CDbl(tmpVal)
    Exit Function
    GetDistance = -1
End Function

Get Google Maps duration (in seconds)

Public Function GetDuration(start As String, dest As String)
    Dim firstVal As String, secondVal As String, lastVal As String
    firstVal = ""
    secondVal = "&destinations="
    lastVal = "&mode=car&language=en&sensor=false"
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+") & lastVal
    objHTTP.Open "GET", URL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("")
    If InStr(objHTTP.responseText, """duration"" : {") = 0 Then GoTo ErrorHandl
    Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = "duration(?:.|\n)*?""value"".*?([0-9]+)": regex.Global = False
    Set matches = regex.Execute(objHTTP.responseText)
    tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))
    GetDuration = CDbl(tmpVal)
    Exit Function
    GetDuration = -1
End Function

Calculate distance between two coordinates

You can calculate the distance between two coordinates (2 pairs of latitudes and longitudes) using either Google’s API or a simple VBA Function.

Calculate distance between coordinates using a VBA function

Taking into account the elliptic nature of Mother Earth you can easily calculate the distance between coordinates without using Google API .

Warning – no the world is not flat as opposed to what the Flat Earch Society is stating

The function returns the distance and using the unit variable you can state if you want the function to return the distance in Kilometres ("K"), Miles ("M") or even nautical miles ("N").

Public Function GetDistanceCoord(ByVal lat1 As Double, ByVal lon1 As Double, ByVal lat2 As Double, ByVal lon2 As Double, ByVal unit As String) As Double
    Dim theta As Double: theta = lon1 - lon2
    Dim dist As Double: dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta))
    dist = WorksheetFunction.Acos(dist)
    dist = rad2deg(dist)
    dist = dist * 60 * 1.1515
    If unit = "K" Then
        dist = dist * 1.609344
    ElseIf unit = "N" Then
        dist = dist * 0.8684
    End If
    GetDistanceCoord= dist
End Function

Function deg2rad(ByVal deg As Double) As Double
    deg2rad = (deg * WorksheetFunction.Pi / 180#)
End Function

Function rad2deg(ByVal rad As Double) As Double
    rad2deg = rad / WorksheetFunction.Pi * 180#
End Function

Calculate distance between coordinates using Google Maps in Excel

To get Google Maps distance between two coordinates simply use the same GetDistance function as above and replace the start and dest parameters with the coordinates in this format:


Final call example:

Debug.Print GetDistance("41.43206,-81.38992", "41.43216,-81.49992")

Same goes for the duration function:

Debug.Print GetDuration("41.43206,-81.38992", "41.43216,-81.49992")

How to set it up in Excel?

Important: Please remember that you need a direct Internet connection! Not via proxy etc.
Follow the steps:

Add new VBA Module

Go to the DEVELOPER ribbon and add select Visual Basic a and new Module to your VBA Project
insert calculate distance macro

Insert the VBA code

Insert the code from sections above (notice that the function is “Public” – therefore will be visible in your workbook as a so called UDF (User Defined Function) add calculate distance macro

Input the function in Excel

Go to the worksheet and input the function as shown below:

=GetDistance("Chicago"; "New York")

Make sure to replace ; with your default formula list separator (e.g. comma in the US)!
Calculate distance between addresses or coordinates

Calculate distance using Google Maps between any number of coordinates/addresses in Excel

Now that we know how to leverage our newly learned GetDistance and GetDuration functions we can use them to measure the distance/duration for any routes, with any coordinates/addresses in between our starting point and our destination. For this I created 2 simple procedures MultiGetDistance and MultiGetDuration:

Get distance between any number of locations

By using our GetDistance function we can get the distance between any number of locations using the Visual Basic procedure below:

Public Function MultiGetDistance(ParamArray args() As Variant) As Double
    MultiGetDistance = 0
    Dim startLoc As String, endLoc As String, i As Long
    For i = LBound(args) To UBound(args) - 1
        startLoc = args(i): endLoc = args(i + 1)
        MultiGetDistance = MultiGetDistance + GetDistance(startLoc, endLoc)
    Next i
End Function

Below example usage:

=MultiGetDistance("Chicago";"New York";"San Jose")

And here is the output:

Calculate distance using Google Mapsbetween multiple addresses
Get Google Maps distance between multiple addresses

Get duration between any number of locations

Similarly by using our GetDuration function we can get the duration between any number of locations using the Visual Basic procedure below:

Public Function MultiGetDuration(ParamArray args() As Variant) As Double
    MultiGetDuration = 0
    Dim startLoc As String, endLoc As String, i As Long
    For i = LBound(args) To UBound(args) - 1
        startLoc = args(i): endLoc = args(i + 1)
        MultiGetDuration = MultiGetDuration + GetDuration(startLoc, endLoc)
    Next i
End Function

Below example usage:

=MultiGetDuration("Chicago";"New York";"San Jose")

Parameters for calculating the Google Maps Distance

The following parameters are available in the API query:

Param Description
key Your application’s API key. This key identifies your application for purposes of quota management. Learn how to get a key from the Google Developers Console.
mode (defaults to driving) — Specifies the mode of transport to use when calculating distance. Valid values and other request details are specified in the Travel Modes section of this document. Other modes:

  • driving (default) for road network.
  • walking for pedestrian paths & sidewalks (where available).
  • bicycling for bicycling via bicycle paths & preferred streets (where available).
  • transit for public transit routes (where available).
language The language in which to return results. See list here
avoid Restrictions to the route. Available:

  • avoid=tolls
  • avoid=highways
  • avoid=ferries
units Unit system to use when expressing distance as text. Available:

  • units=metric (fordistances in kilometers and meters)
  • units=imperial

For other parameters see the original Google Distance Matrix API page:
The Google Distance Matrix API

Limits and common issues

Read more on the limitations of the Google Distance Matrix API here:
The Google Distance Matrix API

Google limits the amount of free queries to the following:

  • 100 elements per query.
  • 100 elements per 10 seconds.
  • 2 500 elements per 24 hour period.
There is a way around these limitation via the use of HTTP Proxies. Read more here.

So beware of any mass recalculation of these functions as you may quickly find yourself exceeding these limits.

Is the function returning -1 or simply not working properly? Be sure you have a direct Internet connection! The XMLHttpRequest Object above is not configured to handle proxy servers common for Office environments.

Common issues

The functions above are not full proof and don’t take into account:

  • That Google won’t find the exact addresses and will approximate with a similar address (see component filtering for more precision)
  • That Google might return several matches. While the function takes the first one from the returned list
  • HTTP or timeouts. See my Web Scraping Kit for how I dealt with such
  • That distances/duration differ depending on which location is set as origin and which is set as destination (one way roads, detours etc.)

Having trouble with matching a large dataset with distances and durations? Reach out for a free quote.

Download an example

You can download an example of the above here:


Need help with calculating the distance between two addresses using the approach above? Feel free to comment below or ask a new Question via Questions page.

Next steps

Want to get the geolocation (coordinates) of any address?
Excel: Get geolocation (coordinates) of any address
Want to add maps and other cool Google Charts in Excel?
Excel: Google Charts Tool
Want to use Google translate in Excel?
Excel: Google Translate functionality

Related Posts

127 thoughts on “Excel VBA Calculate distance between two addresses or coordinates”

    1. Error Message : “tination_addresses” : [],
      “error_message” : “You have exceeded your daily request quota for this API.”,
      “origin_addresses” : [],
      “rows” : [],
      “status” : “OVER_QUERY_LIMIT”

      Is there any way we can have unlimited query limit ?

    2. I am in urgent need of a tool that does exactly this for a network study. It worked temporarily for samples I was putting in manually.

      However, I have a long list of addresses origin – destination, they are all in Europe and when I put in =getdistance(a1, b1) it gives me -1.

      After a couple of tries it also ended up returning -1 for any other manual attempt.

      Having a tool like this at the moment would be vital to me. Any help greatly appreciated. Loved it for the few times it worked for me :_

      1. Hi Raphael, glad it can be of use. I don’t see any reason as to why it shouldn’t work. How many times did you try it? Remember to look at this section: where I mention the limits of using the Google Distance Matrix API. Maybe you exceeded the limit of 100 calls/10 sec? Try running it from VBA instead of as an UDF as this will give you more control over the number of executed API calls. Also keep in mind that the API call might not work if executed behind a proxy.

        Is it only for long distance destinations? If so try analyzing the API call itself (by pasting the URL String from line 7 in your browser window) and see what is returned.

      1. I’m getting the same issue as Jackb. I have verified that “.” is the active character for decimal symbol but the output returns 591 (neither . nor , as separator) when it should be 59.1. Thanks.

        1. Mark,
          Replace the following code shown on line 14:
          tmpVal = Replace(Replace(Replace(Split(tmpVal, " km""")(0), ",", ""), ".", ","), " ", "")
          with this code:
          tmpVal = Replace(Replace(Split(tmpVal, " km""")(0), ",", "."), " ", "")
          This did the trick for me.

          1. Hi Greg,

            I seem to have the same issue where KM are not being separated like Mark described. However I am having an issue with your replacement line. I replaced line 14 with your suggested and I get a #Value error. but I think it’s because the line 14 I am replacing is nothing like your line 14, I used the one provided in the code above: tmpVal = Replace(matches(0).SubMatches(0), “.”, Application.International(xlListSeparator)). Should I be injecting the code you recommend into this line as the replacement doesn’t work?

            Thank you :)

  1. Hi,
    Thank you for the script it is working fine for me. However I also want do use the element duration. Basically the same question as Fábio. Can this be done by changing something in the script and make the function GetDuration? Thanks!

      1. Hi Fredzînho,

        try debugging the actual function line by line (F8) and report which line is throwing an error. Remember that the XMLHttpRequest object above is not configured for proxy so you need a direct Internet connection (corporate networks usually run via proxy). I am planning to add proxy configs for the future.

        1. Hi, first of all thank you for your code and explanation: it’s very elegant and clear.
          However, as I work behind a proxy I have been trying to get around the limitation of XMLHttpRequest to try and run the function on my work computer. I have experimented with WinHttp.WinHttpRequest.5.1 but had no success. Have you ever had a chance to work a version of your function that can authenticate a proxy?
          Thanks in advance.

  2. This is fantastic!

    I hate to ask, but is it possible to get a US localized version that uses miles and is set to use “.” as the decimal as opposed to “,”? I’ve been trying to tinker with the code above, but to no avail.

  3. Hello ,

    I really liked the code. This is somewhat similar to what i was looking for.
    It would be great if you could help me with a code to Getdistance between latitude and longitude of multiple addresses.

    Thank you,

      1. Hey Thomas,

        Thank you!! There is no error while running the code.
        But, it takes around 20 seconds to process and finally gives me #Value! error in the cell.

        Can you please suggest what needs to be done?


  4. Hi, I set this all up in my spreadsheet yesterday and it was working wonderfully but today, when I opened my spreadsheet, all my distance cells show -1! I enabled macros and everything and since I’m new to VBA and coding, I haven’t the slightest clue where to even start looking for the problem…..please help!

    Thank you in advance….I love this function!

    1. Hi Sonya,
      That suggests there was an error in the VBA code. Did you lose you Internet connection? Are you connecting via a Proxy (office/public WLAN often) – if yes then try changing it. Otherwise add a breakpoint to the VBA code (on the second line best) and step through the code (hitting F8). Share the info on which line of code there was an error thrown.

      This might also happen due to there being a momentary break in your Internet connection therefore you might need to recalculate the values manually (edit and hit ENTER on the cell). If you want to make the VBA UDF function to refresh automatically try adding this code at the beginning of the VBA:


  5. This is soooo cool!

    Quick question, I am trying to copy text from a Cell or Text Box, into the Functions.
    I tried:
    =GetDistance(“=A1”, “Adelaide”) and =GetDistance(“Text.Box1.Text”, “Adelaide”)
    To no avail.

    My VBA is limited, but it needs to be edited right? Something around here…?
    URL = firstVal & Replace(start, ” “, “+”) & secondVal & Replace(dest, ” “, “+”) & lastVal

    P.S: This is a fantastic API. I am amazed!!

    1. Hi Joshua,
      glad you like it. First let me know if the example on my page works for you.
      Most certainly text from others cells can be an argument for the GetDistance Google function like below:

      =GetDistance(A1, "Chicago")

      Not sure however bout the TextBox, however, you can go around this creating and UDF for the TextBox (ActiveX) like below:

      Public Function GetTextBoxText()
      GetTextBoxText= Worksheets("Sheet1").TextBox1.Text
      End Function

      Make sure to replace the Sheet1, name of the textbox and put the UDF in a VBA Module (not the Sheet).

      This is an example effect:

      =GetDistance(GetTextBoxText(), "Chicago")

  6. Hi Tom,

    Thanks for your code. Now I have a list (>1000) records of lat and long of addresses and I need to get the distance between two lat long with just a click of a button.
    And this should repeat for the >1000 rows present.

    It needs to connect to Bing maps , to obtain the distance .Can you please help with a code for this?


  7. Greetings! Love it! HUGE time saver. I have a question.

    I’m using this find distance and time from one origin to many destinations. When I had it in use between 1000 to 2000 rows, excel became groggy due to processes/calculations. My computer is a nice one.
    Does this automatically update? Does it require continuous internet even after original calculation? Any way to change it so after first look up it stay static?

    1. Hi Chris,

      glad you find it useful. The function should not update every time (unless you have Application.Volatile=True set at the beginning of the function which you should replace with Application.Volatile=False). If for some reason you are seeing some unnecessary recalculations happening I can suggest several options:

      1. Check if you are not refreshing any of the parameters of the functions by updating other cells
      2. Simply copy and replace the formula with the current value
      3. Change the calculation method to manual and write a macro that would manually recalculate only the needed cells or turn on automatic recalculation only when needed
      4. Extend the function VBA to use a global dictionary of connections (before connecting to Google you would need to look up the connection in the dictionary for an existing connection)
  8. Hi,

    how to get this line of code “If InStr(objHTTP.responseText, “””distance”” : {“) = 0 Then GoTo ErrorHandl”
    to get the distance Text Value “15Mi “not the Distance Value “24663”.
    “rows” : [
    “elements” : [
    “distance” : {
    “text” : “15.3 mi”,
    “value” : 24663
    “duration” : {
    “text” : “23 mins”,
    “value” : 1406
    “status” : “OK”
    “status” : “OK”

    1. I fixed myself, being stupid, change this line of code to this and work as charm, Set regex = CreateObject(“VBScript.RegExp”): regex.Pattern = “””text””.*?([0-9]+)”: regex.Global = False

      Thanks for your example

  9. hi! i am an amateur but your instructions were very obvious. Thanks a lot.
    i’ve noticed that there is a difference between the distance from this macro and that from google map. Is there any explanation? in a distance of 20 km there is a difference of 2.5 km. In other example of distance 1 km the difference is 0.5.
    sometimes bigger and sometimes smaller. Am i doing smth wrong?
    i feel grateful anyway!!

  10. Thank you for sharing this nice solution

    I use it and it work perfectly until yesterday. Now it gives me only 0. I don’t understand why.
    I think that is because google changes his programmation. Somebodyelse have same problem ?

    Before it crashed, I noted problems like ifotiad : little differences between manual and excel estimations. Where do you change query parameters in the code ?

    1. Did you check the restrictions? Checkout the bottom of the post where I mention the restrictions Google puts on the usage of this query (limited amount of queries a day etc.). Let me know if this helps.

  11. I’m novice in VBA (less than one week) so I don’t understand some things. When cells dependent to the function refresh ? Because I have more than 50 queries and if it refresh automaticaly at same time, it can explain why sometimes, all datas become 0.

    I have an other question, I probably missed something, but where in the code you change “PARAMETERS FOR CALCULATING THE GOOGLE MAPS DISTANCE”.

    1. I’m novice in VBA (less than one week) so I don’t understand some things. When cells dependent to the function refresh ? Because I have more than 50 queries and if it refresh automaticaly at same time, it can explain why sometimes, all datas become 0.

      Cells refresh when opening / closing / saving / recalculating / modifying a cell. Automatic recalculation refreshes so called “dirty” cells – e.g. cells for which dependent parameters have been modified (being other cells) or if for some other reason Excel decides to refresh them. If you modify a parameter of all 50 queries I would expect they will refresh instantly in Automatic calculation mode. I personally prefer more control and have a macro that goes through the list of locations/coordinates. This way I can control when and how often these queries will occur.

      I have an other question, I probably missed something, but where in the code you change “PARAMETERS FOR CALCULATING THE GOOGLE MAPS DISTANCE”.

      This is done when building the URL. Look through my code for this part. See the mode, car and sensor?

      firstVal = ""
      secondVal = "&destinations="
      lastVal = "&mode=car&language=pl&sensor=false"

  12. Ok, thank you for your help !

    About the parameters, you should give some exemple of the url changes. Because I see where you can change car to bike, but where do you add avoiding highway or others parameters ?

    1. Thx for the tip. I was sure this was straightforward looking at the other GET params.

      To add params simply append the params to the url preceded with a “&” e.g. add &avoid=highways to the URL

  13. This made my week. Month? Summer? I have to calculate distances between ~30,000 coordinate sets, and after reading this I had it working in a few minutes. Suddenly not a scary task! Thank you so much.

    1. Couple of common issues to check:
      1. You must have a direct internet connection (no office proxy as the XMLHttpRequest object is not configured to handle one)
      2. You may have overrun the Google API limit if you tried recalculating a lot of these functions at once (see the section on the usage limits)

      Let me know if this is none of the above.

    1. Hi Dirk,

      sure you can. Simply add a few lines with a Dictionary object where the keys are strings named by destination and starting point e.g. in a format “[Start address][End Address]”. Then the function instead of querying Google Distance Matrix API should first verify if there is an existing connection in the Dictionary.

      This will still need to recalculate when you close & reopen your Workbook as VBA project data will be lost. If you want your calculations to be done once you have at least two options:
      1. Save your Dictionary to a binary file on Workbook.BeforeClose event. Load it on Workbook.Open event.
      2. Instead of running the function as a UDF (an Excel formula) run it via VBA procedure (one-off calculation).

  14. Hello,

    if I run the VBA-Code, it says, that the “Argument is not optional” in this line:
    URL = firstVal & Replace(start, ” “, “+”) & secondVal & Replace(dest, ” “, “+”) & lastVal
    Have you an idea what the problem is?



    1. Hi Philipp, seemed liked indeed I got an error when running the code (I admit to making a minor tweak recently). However, it turned out to be in another line than you suggested. I ran both procedures (GetDistance and GetDuration) and they returned both correct results.

      Try rerunning the code and see if it works for you too. Otherwise the error you suggested (Argument not optional) happens when a VBA procedure is provided with too little arguments – in this case Replace requires 3 arguments. However in the line you suggested it doesn’t seem like any procedure is missing an argument.

    1. Hi Tony,

      yes this can happen if you are executing the script via proxy (see this section). You need a direct internet connection.

      Otherwise try maybe debugging the script (F8 in VBA Project) line by line and share the line in which you are getting an error.

      1. Hi Tony, glad it started working. It calculates in meters not in miles. Feel free to execute the code from VBA and copy the URL variable to your browser you will have the direct output from Google Distance Matrix.

        Change the “language=pl” to e.g. “language=en” or “language=en-US” of the Google Query in VBA. I believe the language abbreviations are correct otherwise – see full list of country abbreviation here. This should change the values from meters to miles or other US metric.

  15. Hi this is a really wonderful tool. Thanks for putting this together.

    Do you know what the output duration is? I’m curious if this is average duration time or it is calculated differently (including traffic or not). I see that real-time duration data (including traffic) seems to be reserved for Google Maps API for Work customers only.

    Thank you!

  16. I signed up for a Google Maps API key, but every time I add it to the “lastVal” line it creates an error.
    lastVal = “&mode=car&language=en-US&sensor=false&key=###########”

    Is there somewhere else I should be adding it?
    Thanks, Tom

    1. Hi Tom,
      frankly I don’t use a API key at all (notice my examples lack the key). The key is needed if you subscribed to Google API for a Premium Usage Limit or want to use the Pay as you go service. Try removing the key and see if the query link works (generates a proper JSON result). If it’s just the key Contact Google Sales for help.

      Let me know!

    2. Hi Tom,

      Did you ever figure out how to use the key as well? I need to make over 40,000 calls to the service which will be quickly blocked I am sure as I exceeded the 2500 hits in less than a minute. So I too also signed up for the pay as you go and I put my key # in the same location you referenced and I get -1 values as my result.

      I am open to thoughts and suggestions.

      Thank you

  17. Hi

    i am trying to use your code within my excel sheet. I have activated MS XML 6.0 in VBA.
    But nevertheless the code is rather unstable. I am calculating distance for three different start and destination sets and after some time the system gives me #Value error.

    I have searched through your forum but did not find anything to resolve this problem. Kindly help.


      1. No i dont think so since the system starts responding after a few minutes before it goes into the sleep mode again. When you refer to 100 elements per query, do you mean 100 requests of get distance. As i said my program asks for only 3 values.


  18. Hi,
    The code is awesome, however I could calculate the distance only between two places (“New York”; “Las Vegas”).

    Indeed, if I try to include one more place (“New York”; “Las Vegas”;”Miami”), I’ll get back an error…

    How could I resolve it?

    Tnks so much!

  19. Great idea!
    Thank you!

    There is just one more thing whom I wish to be fixed as soon as possible….

    If I use the standard web-based google maps service, and I search for a place, I’ll get the one (in line with the name that I write…) closest to the starting point that I wrote.

    However, your useful script do not use the same procedure!

    Indeed, looking for the distance between a place and another one whom have the same name of many others, the result could be wrong!

    There is a way to fix it?


    1. Hi Alessandro,
      the Google Maps services is more complex than the simple Google Distance Matrix API. I am assuming that it is possible to use other Google API to achieve what you are suggesting. It would probably be quite a complex procedure, hence I am not planning currently to explore these options. What is more I think it is not a good practice to assume that Google will always get the location right if you are not providing it with sufficient details (address or coordinates).

      But I certainly recommend looking into Google API and looking for some ideas to tackle this issue: Let me know if you do manage to solve this somehow!

    1. Hi Magellan,
      1000 m = 1 km. Simply divide by 1k to get km. To get results for bike use my Google Distance Matrix Builder above or add “&mode=bicycling”. Hope that helps

  20. Hi, I’ve received a “Compile error: Variable not defined”

    -> Set objHTTP = CreateObject(“MSXML2.ServerXMLHTTP”)

    Also, we’re unable to move on to IE 11 as some of our older apps can only work on IE 8.

    Is it possible to change the code to use Chrome or Firefox and bypass the use of IE 8?


  21. Hello together
    i need this VBA-skript for MAC Excel2011, can you help me, please?
    Thank you very much!!!

    Public Function Entfernung _
    ( _
    Start_Strasse As String, Start_Stadt_PLZ As String, _
    Start_Bundesland As String, Start_Staat As String, _
    Ziel_Strasse As String, Ziel_Stadt_PLZ As String, _
    Ziel_Bundesland As String, Ziel_Staat As String _

    Dim surl As String
    Dim oXH As Object
    Dim bodytxt As String

    surl = “” & _
    Replace(Start_Strasse, ” “, “+”) & “+” & Replace(Start_Stadt_PLZ, ” “, “+”) & “+” & _
    Replace(Start_Bundesland, ” “, “+”) & “+” & Replace(Start_Staat, ” “, “+”) & _
    “&destinations=” & _
    Replace(Ziel_Strasse, ” “, “+”) & “+” & Replace(Ziel_Stadt_PLZ, ” “, “+”) & “+” & _
    Replace(Ziel_Bundesland, ” “, “+”) & “+” & Replace(Ziel_Staat, ” “, “+”) & _

    Set oXH = CreateObject(“msxml2.xmlhttp”)

    With oXH
    .Open “get”, surl, False
    bodytxt = .responseText
    End With

    bodytxt = Right(bodytxt, Len(bodytxt) – InStr(1, bodytxt, “”) – 5)
    bodytxt = Right(bodytxt, Len(bodytxt) – InStr(1, bodytxt, “”) – 6)
    Entfernung = Left(bodytxt, InStr(1, bodytxt, “”) – 1) / 1000

    Set oXH = Nothing

    End Function

  22. Hello,
    I am a completely new user of VBA. I found your website searching for the information regarding measuring the distance between coordinates based on GPS mode. In my opinion you do a great job!
    I managed to copy and activate the code you pasted for distance between two or more adresses. And it worked. Unfortunately I am not able to: “get Google Maps distance between two coordinates”.
    I would be gratefull for your kind help :)
    Thanks and best regards,

  23. Thanks so much for this code! I am novice at VBA, but have it working. I have read through all the posts, and searched code for the parameter to change from meters to miles and cannot figure it out. Could you share how to make this change in the code? Thanks

    1. Hi Shelli, glad it helped. Simply multiply the km assuming 1 km = 0.621371 mile. Or 1 m = 0.000621371 mile.

      Google does allow you to change the units in the query (changing the text response approximated to miles) but provides the detailed value response still in meters. Hence it makes more sense simply to multiply the km or m to convert to miles by self.

  24. This is a great little snippet of code. I’m currently behind a corporate firewall but will play with duration when I get home. Is there a way to set a departure or arrival time, instead of just using the current time? Further to this, is it possible to opt for the options ‘best guess’, ‘optimistic’, and ‘pessimistic’?


  25. Hello!
    I used your code to get distances and it worked perfect! However when I use the code for duration it always comes back with #value!
    It is weird that my internet connection is working with one code but not with the other, do you know why this might be happening and what can I do to solve it?

    Thank you!

  26. Hello,

    I’m a complete novice with VBA and am having some issues with your code. I’m using this code specifically for calculating distance between locations in the UK. The issue I’m having is that when I try to calculate the distance between towns or cities in the UK where there is a place with the same name in the US, (such as Cambridge), it defaults to the US and throws up an error as it obviously cant find a route from the US to the UK. I can get around the problem by typing +UK at the end of my inputs, but the spreadsheet has other functionality reliant on my not typing +UK at the end – I essentially need to force the VBA function to always add “+UK” to the end of the inputs, how do I do this?

  27. Hello, loving the VBA coding, I am thinking of trying to analyse commuter distance/time using home address and work location, and I think this could be extremely useful.

    One point which I didn’t see mentioned above, and it will likely be to do with Google Maps and not your coding (or it could be an issue with me), but =GetDistance(“Chicago”; “New York”) results in a different answer to =GetDistance(“New York”; “Chicago”), not massively, 1270085 compared to 1271382, but it probably is something to note, as with a few other tests it comes back with varying answers when flipping the destinations around.

    Many thanks

  28. Nope. The ServerXMLHttp request object is not available on Mac. What is more there is nothing remotely close to that. Only option to use QueryTables like this:

    With ActiveSheet.QueryTables.Add(Connection:="URL;", Destination:=Range("A1"))
    .PostText = "origins=Chicago&destinations=New+York&mode=driving&language=en"
    .RefreshStyle = xlOverwriteCells
    .SaveData = True
    End With

  29. Hello,

    This is some incredible stuff! I love it! However, I’m having an issue when it comes to longer distances. Whenever I try to get the distance from say, Seattle to Chicago, I only get a response back of 2. But whenever I put in something closer, say Naperville, IL to Chicago, it works just fine. And I get the same results whether I use an address, a zip code, or just the name of the city.

    Any ideas what is causing this?


    1. Hi Adam, thanks for letting me know. Add this line:

      Debug.Print matches(0).SubMatches(0)

      after/before this one:

      tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlListSeparator))

      and post a new thread on my Forum (VBA) so we don’t junk this post with comments.

      Please post your reply on my Forum (e.g. VBA) so we don’t junk this post with support comments. Thanks!

  30. I got it to work, despite getting a #NAME error at first. I solved this by creating a Add In and then using it that way. That seemed to solve the problem, though I don’t know why. It wouldn’t recognize the UDF any other way.

    But it still doesn’t quite do what I want it to. I need to fetch the longest driving distance. Google maps gives three options of driving distance and I need the longest one.

    Is there a parameter or some way to return that value?

    I am creating an invoice for my process serving (yes, I serve legal papers) and I charge mileage that is the furthest distance as calculated by Google Maps. That is in my contract (it allows for driving around to find someone on obscure addresses)

    Its a pain switching between windows and doing this all manually. I want my invoice spreadsheet to do it automatically.

    This is sooooooo close though! Thanks!

    Maybe you can help me get what I need from this. It seems like a tiny tweak.

    Thank for you help!

    1. Not out of the box. You could potentially use Google Maps Directions API to generate the necessary coordinates. Then translate coordinates to states. And lastly use Google Distance Matrix to measure distances between coordinates and add them to necessary state. This will be quite a lot of work. But perfectly feasible. Reach out to me if you want a quote

  31. Hi!  Can anyone help me with this problem.

    I want to edit the code so that it provides me with distance state wise.  For eg if I am traveling from California to Dallas! Then I want it to show me total distance in California traveled then depending on the route distance in that state traveled till I reach Dallas.

    Please help if you can.




  32. Having trouble reading in values from a cell when calling MultiGetDistance with lng and lat coords.

    If I call using MultiGetDistance(“=A1,B1″,”=A2,B2″,”=A3,B3”)



    I get a #VALUE error. With A1 and B1 being longitude and latitude integer values.

    Great code for helping me get into VBA, thanks for any help


  33. If I type


    I get the desired result, but I am looking to simplify the process so that I am able to type


    Any help is greatly appreciated

  34. I have thousands of addresses in an Excel file that I need to calculate the distance. Can the VBA codes be modified to process a batch of addresses instead of inputting them one by one? For example, I need to calculate distance between addresses in Column A and column B.

    Many thanks!

  35. Thanks for your brilliant code!
    An idea;
    Is it possible to ‘get’ both distance and duration in a single call / single function?

    This might halve the requests to the api and then it would be possible to just extract each value from the cell?

    The json that comes back on googles api page example appears to have both so i think it might be possible ?

  36. Thanks for sharing the code. It is really helpful.

    I tried to bypass google restriction by the use of HTTP proxies (code as follow), but keep getting  #VALUE!

    objHTTP.Open “GET”, URL, False
    objHTTP.setRequestHeader “User-Agent”, “Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)”
    objHTTP.setProxy 2, “##.##.##.##:80”
    objHTTP.send (“”)

    I also tried Google API key, but still getting -1

    lastVal = “&mode=car&language=en-US&sensor=false&key=###########”

    Any help greatly appreciated.


Leave a Reply