By: Lutfor Rahman Shimanto

In reply to Jen.

Dear Jen

Thanks for explaining your requirements clearly. I have reviewed the existing user-defined function and tried to improve it to achieve your goal. The improved user-defined function will try to populate house numbers, roads, cities, states and zip codes by taking Lat and Long values; if any item is missing, it will display an extension like Incomplete!

Follow these steps:

Click on the Developer tab, followed by Visual Basic.

Next, click on Insert, followed by Module.

Paste the following code in the module and save it:
Option Explicit

Function ReverseGeocoder(lati As Double, longi As Double) As String

On Error GoTo ErrorHandler
Dim xD As New MSXML2.DOMDocument
Dim URL As String
Dim house As String
Dim road As String
Dim city As String
Dim state As String
Dim postcode As String

xD.async = False
URL = "https://nominatim.openstreetmap.org/reverse?lat=" + CStr(lati) + "&lon=" + CStr(longi)
xD.Load (URL)

If xD.parseError.ErrorCode <> 0 Then
ReverseGeocoder = "Error: " & xD.parseError.reason
Else
xD.SetProperty "SelectionLanguage", "XPath"

Dim houseNode As MSXML2.IXMLDOMElement
Dim roadNode As MSXML2.IXMLDOMElement
Dim cityNode As MSXML2.IXMLDOMElement
Dim stateNode As MSXML2.IXMLDOMElement
Dim postcodeNode As MSXML2.IXMLDOMElement

Set houseNode = xD.SelectSingleNode("//addressparts/house_number")
Set roadNode = xD.SelectSingleNode("//addressparts/road")
Set cityNode = xD.SelectSingleNode("//addressparts/city")
Set stateNode = xD.SelectSingleNode("//addressparts/state")
Set postcodeNode = xD.SelectSingleNode("//addressparts/postcode")

If Not houseNode Is Nothing Then
house = houseNode.Text
End If

If Not roadNode Is Nothing Then
road = roadNode.Text
End If

If Not cityNode Is Nothing Then
city = cityNode.Text
End If

If Not stateNode Is Nothing Then
state = stateNode.Text
End If

If Not postcodeNode Is Nothing Then
postcode = postcodeNode.Text
End If

If house = "" Or road = "" Or city = "" Or state = "" Or postcode = "" Then
ReverseGeocoder = house & " " & road & ", " & city & ", " & state & ", " & postcode & " [Incomplete!]"
Else
ReverseGeocoder = house & " " & road & ", " & city & ", " & state & ", " & postcode
End If
End If

Exit Function

ErrorHandler:
ReverseGeocoder = "Error: " & Err.Description

End Function

Return to the sheet and choose an empty cell.

Apply the following formula: =ReverseGeocoder(B5,C5)

Drag the Fill Handle icon to copy the formula down.

I hope you have found the user-defined function of reverse geocoding you were looking for. I have attached the solution workbook as well. Good luck.

DOWNLOAD SOLUTION WORKBOOK

Regards
Lutfor Rahman Shimanto
Excel & VBA Developer
ExcelDemy