Você está na página 1de 14

The Analyst Cave | Excel, VBA, programming and more

SKIP TO CONTENT

VBA CHEAT SHEET

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)

JULY 24, 2014 ANALYSTCAVE 131 COMMENTS

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

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.
Lets 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:
1 https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seatt
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.

From:

To:

Mode:

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

1 'Calculate Google Maps distance between two addresses


Public Function GetDistance(start As String, dest As String)
2
Dim firstVal As String, secondVal As String, lastVal As String
3 firstVal = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
4 secondVal = "&destinations="
5 lastVal = "&mode=car&language=pl&sensor=false"
6 Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
7
8
URL = firstVal & Replace(start, " ", "+") & secondVal & Replace(dest, " ", "+"
9 objHTTP.Open "GET", URL, False
10 objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Win
11 objHTTP.send ("")
12 If InStr(objHTTP.responseText, """distance"" : {") = 0 Then GoTo ErrorHandl
Set regex = CreateObject("VBScript.RegExp"): regex.Pattern = """value"".*?([0-9
13 Set matches = regex.Execute(objHTTP.responseText)
14 tmpVal = Replace(matches(0).SubMatches(0), ".", Application.International(xlLi
15 GetDistance = CDbl(tmpVal)
16 Exit Function
17 ErrorHandl:
GetDistance = -1
18 End Function
19
20
Get Google Maps duration (in seconds)

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.

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").
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

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:
1 41.43216,-81.49992
Final call example:

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


Same goes for the duration function:

1 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 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)

Input the function in Excel

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

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


Make sure to replace ; with your default formula list separator (e.g. comma
in the US)!

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:
1 Public Function MultiGetDistance(ParamArray args() As Variant) As Double
MultiGetDistance = 0
2
Dim startLoc As String, endLoc As String, i As Long
3
4 For i = LBound(args) To UBound(args) - 1
startLoc = args(i): endLoc = args(i + 1)
5 MultiGetDistance = MultiGetDistance + GetDistance(startLoc, endLoc)
6 Next i
7 End Function
8
Below example usage:

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


And here is the output:

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:
1
Public Function MultiGetDuration(ParamArray args() As Variant) As Double
2 MultiGetDuration = 0
3 Dim startLoc As String, endLoc As String, i As Long
4 For i = LBound(args) To UBound(args) - 1
5 startLoc = args(i): endLoc = args(i + 1)
MultiGetDuration = MultiGetDuration + GetDuration(startLoc, endLoc)
6
Next i
7 End Function
8
Below example usage:

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

Parameters for calculating the


Google Maps Distance
The following parameters are available in the API query:

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

Restrictions to the route. Available:


avoid=tolls
avoid=highways
avoid avoid=ferries

Unit system to use when expressing distance as text. Available:


units=metric (fordistances in kilometers and meters)
units 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.
2500 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 dont take into account:

That Google wont 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:

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

Visual Basic Editor Tutorial for Excel How...

Excel Substring and VBA Substring Left, R...

Native VBA Multithreading? There is only 1 butR...


GOOGLE MAPSMACROMAPUDFUSER DEFINED FUNCTIONVBA
NEXT POSTGet Google Maps address coordinates (latitude & longitude) in
Excel VBA

TABLE OF CONTENTS

1 Using the Google Maps Distance Matrix API


2 Calculate distance between two addresses using Google Maps in Excel
3 Calculate distance between two coordinates
4 How to set it up in Excel?
5 Calculate distance using Google Maps between any number of
addresses in Excel
6 Parameters for calculating the Google Maps Distance
7 Limits and common issues
8 Download an example
9 Help!
10 Next steps
Simply the best place to learn VBA!

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

Public Structure Graph


Public VerticesCount As Integer
Public EdgesCount As Integer
Public edge As Edge()
End Structure

Public Structure Subset


Public Parent As Integer
Public Rank As Integer
End Structure

Public Shared Function CreateGraph(verticesCount As Integer, edgesCoun As Integer) As


Graph
Dim graph As New Graph()
graph.VerticesCount = verticesCount
graph.EdgesCount = edgesCoun
graph.edge = New Edge(graph.EdgesCount - 1) {}

Return graph
End Function

Private Shared Function Find(subsets As Subset(), i As Integer) As Integer


If subsets(i).Parent <> i Then
subsets(i).Parent = Find(subsets, subsets(i).Parent)
End If

Return subsets(i).Parent
End Function

Private Shared Sub Union(subsets As Subset(), x As Integer, y As Integer)


Dim xroot As Integer = Find(subsets, x)
Dim yroot As Integer = Find(subsets, y)

If subsets(xroot).Rank < subsets(yroot).Rank Then


subsets(xroot).Parent = yroot
ElseIf subsets(xroot).Rank > subsets(yroot).Rank Then
subsets(yroot).Parent = xroot
Else
subsets(yroot).Parent = xroot
subsets(xroot).Rank += 1
End If
End Sub

Private Shared Sub Print(result As Edge(), e As Integer)


For i As Integer = 0 To e - 1
Console.WriteLine("{0} -- {1} == {2}", result(i).Source,
result(i).Destination, result(i).Weight)
Next
End Sub

Public Shared Sub Kruskal(graph As Graph)


Dim verticesCount As Integer = graph.VerticesCount
Dim result As Edge() = New Edge(verticesCount - 1) {}
Dim i As Integer = 0
Dim e As Integer = 0

Array.Sort(graph.edge, Function(a As Edge, b As Edge)


a.Weight.CompareTo(b.Weight))

Dim subsets As Subset() = New Subset(verticesCount - 1) {}


For v As Integer = 0 To verticesCount - 1
subsets(v).Parent = v
subsets(v).Rank = 0
Next

While e < verticesCount - 1


Dim nextEdge As Edge = graph.edge(i)
Dim x As Integer = Find(subsets, nextEdge.Source)
Dim y As Integer = Find(subsets, nextEdge.Destination)
i += 1

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)

' Edge 0-1


graph.edge(0).Source = 0
graph.edge(0).Destination = 1
graph.edge(0).Weight = 10

' Edge 0-2


graph.edge(1).Source = 0
graph.edge(1).Destination = 2
graph.edge(1).Weight = 6

' Edge 0-3


graph.edge(2).Source = 0
graph.edge(2).Destination = 3
graph.edge(2).Weight = 5

' Edge 1-3


graph.edge(3).Source = 1
graph.edge(3).Destination = 3
graph.edge(3).Weight = 15

' Edge 2-3


graph.edge(4).Source = 2
graph.edge(4).Destination = 3
graph.edge(4).Weight = 4

Kruskal(graph)
Output

2 -- 3
== 4
0 -- 3 == 5
0 -- 1 == 10

Excel Gantt Chart TutorialExcel VBA Evaluate Tips and Tricks to

Você também pode gostar