Function to extract Zip/Pin code using Regular Expressions in Excel

REGEX are powerful irrespective of language. All you need to be aware is its usage. You can check any reference for syntax. There are thousands available over web.

In this example, we write a function that extracts zip/pin code from the address.


Function getZip(addr As String)

Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.Pattern = "(\d{6})"
RE.Global = True
RE.IgnoreCase = True

Set allMatches = RE.Execute(addr)

If (allMatches.Count <> 0) Then
    result = allMatches.Item(0).submatches.Item(0)
End If

getZip = result
End Function


After writing this function when you put =getZip("Flat No 260, Building No 17, , Thane West, Thane - 400601, Near Vasant Vihar School") in A1, the output would be 400601.

You can watch this tutorial to learn it in detail:

 

 


You can post your questions/comments below.