Está en la 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

The API is configured using GET HTTP Params. Say we want to get the distance between San Francisco and Victoria BC. Of course open Google Maps and type each location one by one… and then choose the shortest connection. Let’s however focus on getting the distance between two addresses.48 out of 5) JULY 24. average: 4. 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. Google facilitates Google Maps Distance Matrix API for limited usage.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seatt . A simple example below. 50 administration offices across my city I wanted to find the one that is closest to my workplace.EXCEL VBA CALCULATE DISTANCE BETWEEN TWO ADDRESSES OR COORDINATES (25 votes. Copy this link into your browser: 1 https://maps. 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.googleapis. We want to get there by bicycle.

CA. Go here for more options for configuring the Google Maps Distance Matrix API. secondVal As String. dest As String) 2 Dim firstVal As String. 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. Google Distance between Vancouver. Simply type in the From an To addresses.ServerXMLHTTP") .com/maps/api/distancematrix/json?origins=" 4 secondVal = "&destinations=" 5 lastVal = "&mode=car&language=pl&sensor=false" 6 Set objHTTP = CreateObject("MSXML2. lastVal As String 3 firstVal = "http://maps. BC.googleapis. 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. select the transportation mode and hit Build URL!. USA Google Distance Matrix Builder Want to quickly test the Google API? Below a simple form for building a quick Distance URL. Canada and San Francisco.

False 9 objHTTP. "Mozilla/4. "Mozilla/4. ".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.SubMatches(0).send ("") 12 If InStr(objHTTP. lastVal As String 4 firstVal = "http://maps. " ".Execute(objHTTP.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 Google’s API or a simple VBA Function. " ".ServerXMLHTTP") 7 URL = firstVal & Replace(start. secondVal As String.send ("") 11 If InStr(objHTTP. Win 10 objHTTP.Open "GET".".com/maps/api/distancematrix/json?origins=" 5 secondVal = "&destinations=" 6 lastVal = "&mode=car&language=en&sensor=false" Set objHTTP = CreateObject("MSXML2.0 (compatible.".responseText) 14 tmpVal = Replace(matches(0). False 10 objHTTP. Win 11 objHTTP. Application.responseText) 13 tmpVal = Replace(matches(0). """distance"" : {") = 0 Then GoTo ErrorHandl Set regex = CreateObject("VBScript. " ". ". MSIE 6. URL.7 8 URL = firstVal & Replace(start.0.setRequestHeader "User-Agent". Application.Pattern = "duration(?:.SubMatches(0). URL.googleapis.|\n)* 12 Set matches = regex.RegExp"): regex.Pattern = """value"". "+") & secondVal & Replace(dest.Execute(objHTTP. " ".0.setRequestHeader "User-Agent". "+") & secondVal & Replace(dest. MSIE 6.responseText.RegExp"): regex. . dest As String) 3 Dim firstVal As String. """duration"" : {") = 0 Then GoTo ErrorHandl Set regex = CreateObject("VBScript. "+" 8 objHTTP. "+" 9 objHTTP.Open "GET".0 (compatible.*?([0-9 13 Set matches = regex. 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 .responseText.

Pi / 180#) 1 End Function 6 1 Function rad2deg(ByVal rad As Double) As Double 7 rad2deg = rad / WorksheetFunction.49992 Final call example: 1 Debug.lon2 Dim dist As Double: dist = Math. ByVal lat2 A 9 Dim theta As Double: theta = lon1 .609344 ElseIf unit = "N" Then 1 dist = dist * 0.38992".43216.-81.43206.-81. ByVal lon1 As Double.8684 3 End If 1 GetDistanceCoord= dist 4 End Function 1 5 Function deg2rad(ByVal deg As Double) As Double deg2rad = (deg * WorksheetFunction.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"). "41.Print GetDistance("41. 1 2 3 4 5 6 7 8 Public Function GetDistanceCoord(ByVal lat1 As Double.49992") .1515 1 If unit = "K" Then 2 dist = dist * 1.-81.Acos(dist) 0 dist = rad2deg(dist) 11 dist = dist * 60 * 1.Sin(deg2rad(lat2)) + Math 1 dist = 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. Miles ("M") or even nautical miles ("N").43216.Sin(deg2rad(lat1)) * Math.

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".43216. "41.-81. "New York") .43206.Same goes for the duration function: 1 Debug.38992".49992") How to set it up in Excel? Important: Please remember that you need a direct Internet connection! Not via proxy etc.Print GetDuration("41.-81.

endLoc As String. with any coordinates/addresses in between our starting point and our destination.g. i As Long . with your default formula list separator (e. 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. 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.Make sure to replace .

1 startLoc = args(i): endLoc = args(i + 1) 5 MultiGetDistance = MultiGetDistance + GetDistance(startLoc."San Jose") Parameters for calculating the Google Maps Distance The following parameters are available in the API query: PARAM DESCRIPTION Your application’s API key. endLoc) 6 Next i 7 End Function 8 Below example usage: 1 =MultiGetDistance("Chicago"."New York".  walking for pedestrian paths & sidewalks (where available). i As Long 4 For i = LBound(args) To UBound(args) ."New York". . 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. Learn how to get a key from the Google Developers Console. This key identifies your application for purposes of quota key management. endLoc) 6 Next i 7 End Function 8 Below example usage: 1 =MultiGetDuration("Chicago". Other modes:  driving (default) for road network."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.3 4 For i = LBound(args) To UBound(args) .1 5 startLoc = args(i): endLoc = args(i + 1) MultiGetDuration = MultiGetDuration + GetDuration(startLoc. endLoc As String.

Available:  avoid=tolls  avoid=highways avoid  avoid=ferries Unit system to use when expressing distance as text. There is a way around these limitation via the use of HTTP Proxies.  bicycling for bicycling via bicycle paths & preferred streets (where available). So beware of any mass recalculation of these functions as you may quickly find yourself exceeding these limits. 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. langua ge The language in which to return results.  100 elements per 10 seconds. See my Web Scraping Kit for how I dealt with such .  transit for public transit routes (where available). 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. See list here Restrictions to the route. 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.  2 500 elements per 24 hour period. While the function takes the first one from the returned list  HTTP or timeouts. Read more here.

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. detours etc... 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 . 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..  That distances/duration differ depending on which location is set as origin and which is set as destination (one way roads.) Having trouble with matching a large dataset with distances and durations? Reach out for a free quote... Native VBA Multithreading? There is only 1 butR.. R. Excel Substring and VBA Substring – Left.

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. then it finds a minimum spanning forest (a minimum spanning tree for each connected component).  C#  VB. 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. where the total weight of all the edges in the tree is minimized.Net  C  C++  PHP  Public Structure Edge Public Source As Integer Public Destination As Integer Public Weight As Integer End Structure Public Structure Graph . If the graph is not connected.

b As Edge) a. y) If subsets(xroot). edgesCoun As Integer) As Graph Dim graph As New Graph() graph.Parent = Find(subsets. i As Integer) As Integer If subsets(i). result(i). x) Dim yroot As Integer = Find(subsets.1) {} Dim i As Integer = 0 Dim e As Integer = 0 Array. result(i).Weight.Parent = yroot ElseIf subsets(xroot).1 Console.Rank += 1 End If End Sub Private Shared Sub Print(result As Edge().WriteLine("{0} -.CompareTo(b. x As Integer.Source. y As Integer) Dim xroot As Integer = Find(subsets.Rank Then subsets(yroot). 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.VerticesCount Dim result As Edge() = New Edge(verticesCount .Rank < subsets(yroot).edge = New Edge(graph.{1} == {2}".EdgesCount . e As Integer) For i As Integer = 0 To e .Parent <> i Then subsets(i).Parent = xroot subsets(xroot). subsets(i).1) {} . result(i).VerticesCount = verticesCount graph.Weight)) Dim subsets As Subset() = New Subset(verticesCount .Parent = xroot Else subsets(yroot).edge.Parent) End If Return subsets(i).Rank > subsets(yroot).Destination.Rank Then subsets(xroot).EdgesCount = edgesCoun graph. Function(a As Edge.1) {} Return graph End Function Private Shared Function Find(subsets As Subset().Weight) Next End Sub Public Shared Sub Kruskal(graph As Graph) Dim verticesCount As Integer = graph.Parent End Function Private Shared Sub Union(subsets As Subset().Sort(graph.

x.edge(4).edge(1).Destination = 3 graph.edge(3). nextEdge.edge(2).edge(4).Weight = 10 ' Edge 0-2 graph.Source = 0 graph.Rank = 0 Next While e < verticesCount . nextEdge.edge(1).Weight = 5 ' Edge 1-3 graph.edge(4).edge(0).Source = 2 graph.edge(3).Destination = 3 graph.Source = 0 graph.Weight = 4 Kruskal(graph) .edge(i) Dim x As Integer = Find(subsets. y) End If End While Print(result.edge(2).edge(0).Source = 0 graph.Parent = v subsets(v).1 subsets(v).Source) Dim y As Integer = Find(subsets.Source = 1 graph.Destination = 2 graph.edge(0).edge(1). e) End Sub Example Dim verticesCount As Integer = 4 Dim edgesCount As Integer = 5 Dim graph As Graph = CreateGraph(verticesCount.Destination = 3 graph.Weight = 15 ' Edge 2-3 graph.edge(3).Destination = 1 graph. For v As Integer = 0 To verticesCount . edgesCount) ' Edge 0-1 graph.edge(2).Destination) i += 1 If x <> y Then result(e) = nextEdge e += 1 Union(subsets.1 Dim nextEdge As Edge = graph.Weight = 6 ' Edge 0-3 graph.

3 == 4 0 -.1 == 10 Excel Gantt Chart TutorialExcel VBA Evaluate – Tips and Tricks to .Output 2 -.3 == 5 0 -.