Skip to content

Instantly share code, notes, and snippets.

@saurabhkaul
Created July 31, 2018 07:23
Show Gist options
  • Save saurabhkaul/37f7c25e562183f275a97a6963e4dd1c to your computer and use it in GitHub Desktop.
Save saurabhkaul/37f7c25e562183f275a97a6963e4dd1c to your computer and use it in GitHub Desktop.
Simple VBA subroutine I wrote for excel in VBA that could extract a pattern(Indian pin code in this case) and output the multiple selections in a column using regex
Private Sub simpleRegex()
Dim strPattern As String: strPattern = "\d{6}" 'Define regex pattern here
Dim Match As Object
Dim matches As Object
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
Dim strInput As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("A1:A200") 'Define the range of column you want the regex to work on
Dim i As Long, strMatches As String
i = 1
For Each cell In Myrange
If strPattern <> "" Then
strInput = cell.Value
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regex.Test(strInput) Then
Set matches = regex.Execute(strInput)
strMatches = vbNullString
For Each Match In matches
strMatches = strMatches & Match.Value & " " 'collect all matches comma seprated
Next
Worksheets(1).Range("B" & i).Value = strMatches 'write the matches into cell of your choice."B" in this case.
i = i + 1
Else
Worksheets(1).Range("B" & i).Value = "No Match" 'write the matches into cell 'Change the value here too
i = i + 1
End If
End If
Next
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment