I am wanting a code to check all postcodes in say column A and turn the cell green if it passes the REGEX pattern and red if it doesn't. I have been using the below code:
sub postcode()
Dim strPattern As String
Dim regEx As Object
Dim ncella As Long, i As Long
Dim rng As Range
Set regEx = CreateObject("VBScript.RegExp")
regEx.Global = True
regEx.IgnoreCase = True
ncella = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlDown).Row
For i = 1 To 2
If i = 1 Then
strPattern = "(\d{4})"
Set rng = Range("A2:A" & ncella)
End If
regEx.Pattern = strPattern
For Each cell In rng.Rows ' Define your own range here
If strPattern <> "" And cell <> "" Then ' If the cell is not empty and there is pattern
If regEx.test(cell.Value) Then ' Check if there is a match
cell.Interior.ColorIndex = 4 ' If yes, change the background color
Else
cell.Interior.ColorIndex = 3
End If
End If
Next
Next i
End Sub
Now I also want to use this check for validating the postcode patterns for several countries so (once my code above or any other code is provided) then I would need the patterns to be validated once the ISO country code is selected by the user, essentially applying the pattern to the specific country.
Hope the above makes sense
Now in the above is a simple check to see if there are 4 digits in the postcode then turn Green. If I paste in a number with 1,2,3 or 4 digits the cell correctly turns red, however if I have 6 or more digits it turns green for some reason. Having 5 digits also turns the cell green which is correct.