This function uses Google Maps (not the API) and returns the distance between 2 addresses. It can called from VBA or as a worksheet cell function. For example with the start address in A1 and the end address in B1, in C1 enter =GMaps_Distance(A1,B1). The addresses can be any address, location, latitude and longitude coordinates, zip code, post code, etc.
Public Function GMaps_Distance(FromAddress As String, ToAddress As String) As String
Static XML As Object
Dim URL As String
Dim HTMLdoc As Object
Dim routeLI As Object
URL = "http://maps.google.com/maps?f=d&source=s_d&saddr=" & Escape(FromAddress) & "&daddr=" & Escape(ToAddress)
If XML Is Nothing Then Set XML = CreateObject("MSXML2.XMLHTTP")
With XML
.Open "GET", URL, False
.send
Set HTMLdoc = New HTMLDocument
HTMLdoc.body.innerHTML = .responseText
End With
GMaps_Distance = ""
Set routeLI = HTMLdoc.getElementById("altroute_0")
If Not routeLI Is Nothing Then
GMaps_Distance = Left(routeLI.innerText, InStr(routeLI.innerText, ", ") - 1)
End If
End Function
Private Function Escape(ByVal paramValue As String) As String
Dim i As Integer, BadChars As String
BadChars = "<>%=&!@#$^()+{[}]|\;:'"",/?"
For i = 1 To Len(BadChars)
paramValue = Replace(paramValue, Mid(BadChars, i, 1), "%" & Hex(Asc(Mid(BadChars, i, 1))))
Next
paramValue = Replace(paramValue, " ", "+")
Escape = paramValue
End Function
Bookmarks