Escolar Documentos
Profissional Documentos
Cultura Documentos
SKIP TO CONTENT
VBA TUTORIALS
o EXCEL VBA TUTORIAL
o WORD VBA TUTORIAL
o WEB SCRAPING TUTORIAL
o EXCEL REGEX TUTORIAL
o VBA PERFORMANCE
o VBA CLASS TUTORIAL
EXCEL TOOLS
o VBA TIME SAVER KIT CODE SNIPPETS & VBA REFERENCE
o VBA WEB SCRAPING KIT EASY SCRAPING FOR EXCEL
o VBA COMPILER (TO VB.NET)
o VBA MULTITHREADING TOOL
o EXCEL SCRAPE HTML ADD-IN
DOCUMENTATION
o GOOGLE CHARTS TOOL
o EXCEL SQL ADD-IN
o EXCEL OPTIMIZER
o HOW TO INSTALL EXCEL ADDINS?
VBA QUESTIONS?
CONTACT
Home Excel VBA Calculate distance between two addresses or
coordinates
EXCEL, GOOGLE API, MS OFFICE, WEB, WEB SCRAPING
EXCEL VBA CALCULATE
DISTANCE BETWEEN TWO
ADDRESSES OR COORDINATES
(25 votes, average: 4.48 out of 5)
FacebookGoogle+TwitterTumblrBlogg
er PostEmail
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:
Between any two ADDRESSES
Between any two COORDINATES
To get the COORDINATES of any ADDRESS read this post
From:
To:
Mode:
1
2
Public Function GetDuration(start As String, dest As String)
3 Dim firstVal As String, secondVal As String, lastVal As String
4 firstVal = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
5 secondVal = "&destinations="
6 lastVal = "&mode=car&language=en&sensor=false"
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
7 URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+"
8 objHTTP.Open "GET", URL, False
9 objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Win
10 objHTTP.send ("")
11 If InStr(objHTTP.responseText, """duration"" : {") = 0 Then GoTo ErrorHandl
Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = "duration(?:.|\n)*
12 Set matches = regex.Execute(objHTTP.responseText)
13 tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlLi
14 GetDuration = CDbl(tmpVal)
15 Exit Function
16 ErrorHandl:
GetDuration = -1
17 End Function
18
19
Calculate distance between two
coordinates
You can calculate the distance between two coordinates (2 pairs of
latitudes and longitudes) using either Googles API or a simple VBA
Function.
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").
1
2
3
4
5
6
7
8 Public Function GetDistanceCoord(ByVal lat1 As Double, ByVal lon1 As Double, ByVal lat2 A
9 Dim theta As Double: theta = lon1 - lon2
Dim dist As Double: dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math
1
dist = WorksheetFunction.Acos(dist)
0 dist = rad2deg(dist)
11 dist = dist * 60 * 1.1515
1 If unit = "K" Then
2 dist = dist * 1.609344
ElseIf unit = "N" Then
1 dist = dist * 0.8684
3 End If
1 GetDistanceCoord= dist
4 End Function
1
5 Function deg2rad(ByVal deg As Double) As Double
deg2rad = (deg * WorksheetFunction.Pi / 180#)
1 End Function
6
1 Function rad2deg(ByVal rad As Double) As Double
7 rad2deg = rad / WorksheetFunction.Pi * 180#
1 End Function
8
1
9
2
0
2
1
Go to the DEVELOPER ribbon and add select Visual Basic a and new Module
to your VBA Project
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)
PARAM DESCRIPTION
Your applications API key. This key identifies your application for purposes of quota
key 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).
langua
ge The language in which to return results. See list here
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.
2500 elements per 24 hour period.
There is a way around these limitation via the use of HTTP Proxies. Read
more here.
Common issues
The functions above are not full proof and dont take into account:
DOWNLOAD EXAMPLE
Help!
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
TABLE OF CONTENTS
RECENT POSTS
Kruskal's Algorithm
Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the
least possible weight that connects any two trees in the forest. It is a greedy
algorithm in graph theory as it finds a minimum spanning tree for a connected
weighted graph adding increasing cost arcs at each step. This means it finds a
subset of the edges that forms a tree that includes every vertex, where the total
weight of all the edges in the tree is minimized. If the graph is not connected, then it
finds a minimum spanning forest (a minimum spanning tree for each connected
component).
C#
VB.Net
C++
PHP
Public
Structure Edge
Public Source As Integer
Public Destination As Integer
Public Weight As Integer
End Structure
Return graph
End Function
Return subsets(i).Parent
End Function
If x <> y Then
result(e) = nextEdge
e += 1
Union(subsets, x, y)
End If
End While
Print(result, e)
End Sub
Example
Dim
verticesCount As Integer = 4
Dim edgesCount As Integer = 5
Dim graph As Graph = CreateGraph(verticesCount, edgesCount)
Kruskal(graph)
Output
2 -- 3
== 4
0 -- 3 == 5
0 -- 1 == 10