Thursday, April 16, 2015

VBA Regular Expression Phone Number Validator

This phone number validator validates numbers with or without dashes and with or without dots between the segments.


Public Function validatePhoneNo(phoneno As String) As Boolean

    If phoneno <> "" Then
        Dim re As RegExp
        Dim matches As MatchCollection
        Set re = New RegExp
        re.IgnoreCase = True
        re.Global = True
        re.Pattern = "^\(?\d{3}-?\.?\)?\s?\d{3}-?\.?\d{4}$"
        Set matches = re.Execute(phoneno)
        If matches.Count <> 1 Then
            validatePhoneNo = False
            Exit Function
        End If
    Else
        validatePhoneNo = False
        Exit Function
    End If
 
    validatePhoneNo = True
 
End Function

1 comment:

  1. I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You.
    microsoft excel vba training

    ReplyDelete