×

VBA Regex Pattern Validation

VBA Regex Pattern Validation

The key purpose of using Regex in VBA was to validate the data and extract the same category of data. There are certain formats that are standard and are followed worldwide. Following those standards, we can extract and list all the values from the excel datasheet just within one click. Below are the few common regex validation patterns used in day to day activities.

  1. Email Validation using Regex

 In email validation, two things are constant, i.e. ‘@’ and ‘.’. With the help of these two characters we have defined the regex pattern. In the first place, we can have as many characters, it will be followed by ‘@’, then again we will have characters (unlike Gmail) followed by ‘.’ and at last ending it characters (com/in/co.in).

Regex Syntax:

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]

Program:

Function EmailRegexValidation(regexStr As String) As Boolean
'***************************************************************
' This function returns the Boolean True if the pattern matches
'***************************************************************
Dim regex As Object
Dim isValidEmail As Boolean
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim emailRegexPattern As String
'the regex pattern for 10-digit phone validation
emailRegexPattern = "([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.])"
With regex
    .Pattern = emailRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the negative numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
'will test the string for the given pattern
isValidEmail = regex.Test(regexStr)
EmailRegexValidation = isValidEmail
End Function
VBA Regex Pattern Validation

Output:

VBA Regex Pattern Validation
VBA Regex Pattern Validation

2. Regex Validation Pattern for Alphanumeric Strings

It must have a combination of alphabets and numbers. It will mostly be used in passwords and hence, alphanumeric strings are classified as Strong passwords.

Regex Syntax:

^((?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,}))

Program:

Function AlphaNumericRegexValidation (regexStr As String) As Boolean
'***************************************************************
' This function returns the boolean True the pattern matches
'***************************************************************
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim phoneNumberRegexPattern As String
'Defining the regex pattern to extract or validate alpha numeric
alphaNumericRegexPattern = "^((?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,}))"
With regex
    .Pattern = alphaNumericRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the negative numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
End Function

3. RegEx Pattern for Positive numbers

It will check for the number which is greater than 0.

Regex Syntax:

^([+]?\d+([.]\d+))

Program:

Function PositiveNumberRegexValidation(regexStr As String) As Boolean
'***************************************************************
' This function returns the boolean True the pattern matches
'***************************************************************
Dim regex As Object
Dim isValidNumber As Boolean
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim positiveNumberRegexPattern As String
'the regex pattern for positive number validation
positiveNumberRegexPattern = "^([+]?\d+([.]\d+))"
With regex
    .Pattern = positiveNumberRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the positive numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
'will test the string for the given pattern
isValidNumber = regex.Test(regexStr)
PositiveNumberRegexValidation = isValidNumber
End Function
VBA Regex Pattern Validation

4. RegEx Validation for Negative numbers (num < 0)

It will check for the number which is smaller than 0.

Regex Syntax:

^(\-\d+([.]?\d+))

Program:

Function NegativeNumberRegexValidation(regexStr As String) As Boolean
'***************************************************************
' This function returns the boolean True the pattern matches
'***************************************************************
Dim regex As Object
Dim isValidNumber As Boolean
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim negativeNumberRegexPattern As String
'the regex pattern for negative number validation
negativeNumberRegexPattern = "(^(\-\d+([.]?\d+)))"
With regex
    .Pattern = negativeNumberRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
'will test the string for the given pattern
isValidNumber = regex.Test(regexStr)
NegativeNumberRegexValidation = isValidNumber
End Function
VBA Regex Pattern Validation

Output

VBA Regex Pattern Validation

5. RegEx Pattern for 10-digit telephone number [not starting with Zero]

It will check for a 10-digit telephonic number. As the first digit can never be 0, so it will check the number from 1-9, and for the next 9 digits, it can take values from 0-9.

Regex Syntax:

[1-9]{1}[0-9]{9}$

Program:

Function PhoneNumberRegexValidation(regexStr As String) As Boolean
'***************************************************************
' This function returns the Boolean True if the pattern matches
'***************************************************************
Dim regex As Object
Dim isValidEmail As Boolean
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim phoneNumberRegexPattern As String
'the regex pattern for 10-digit phone validation
phoneNumberRegexPattern = "[1-9]{1}[0-9]{9}$"
With regex
    .Pattern = phoneNumberRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the negative numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
'will test the string for the given pattern
isValidEmail = regex.Test(regexStr)
PhoneNumberRegexValidation = isValidEmail
End Function
VBA Regex Pattern Validation

Output

VBA Regex Pattern Validation
VBA Regex Pattern Validation

6. RegEx Pattern for Phone with a country code format

It same unlike the above syntax except in this we have added the ‘+’ character and allocated two more digits, which can be from 0-9.

Regex Syntax:

[+]{1}[0-9]{2}[-]{1}[1-9]{1}[0-9]{9}$

Program:

Function PhoneNumberRegexValidation(regexStr As String) As Boolean
'***************************************************************
' This function returns the boolean True the pattern matches
'***************************************************************
Dim regex As Object
Dim isValidEmail As Boolean
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim phoneNumberRegexPattern As String
'the regex pattern for 12 digit phonenumber (along with country code) validation
phoneNumberRegexPattern = "[+]{1}[0-9]{2}[-]{1}[1-9]{1}[0-9]{9}$"
With regex
    .Pattern = phoneNumberRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
'will test the string for the given pattern
isValidEmail = regex.Test(regexStr)
PhoneNumberRegexValidation = isValidEmail
End Function

7. RegEx Pattern for Year between 1900 and 2018

This is helpful to check if the specified year lies in between the range of 1900 – 2018.

Regex Syntax:

(19[0-9]{2}|200[0-9]{1}|201[0-8]{1})$

Program:

Function YearRegexValidation(regexStr As String) As Boolean
'***************************************************************
' This function returns the boolean True the pattern matches
'***************************************************************
Dim regex As Object
Dim isValidYear As Boolean
Set regex = CreateObject("VBScript.RegExp")
Dim matchesVal As Object
Dim yearRegexPattern As String
'the regex pattern for year(between 1900 and 2018) validation
yearRegexPattern = "(19[0-9]{2}|200[0-9]{1}|201[0-8]{1})$"
With regex
    .Pattern = yearRegexPattern
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' All the numbers will be listed in this Object
Set matchesVal = regex.Execute(regexStr)
'Loop reading all the matches found
For Each Item In matchesVal
    Debug.Print Item.Value
Next
'will test the string for the given pattern
isValidNumber = regex.Test(regexStr)
YearRegexValidation = isValidNumber
End Function
VBA Regex Pattern Validation

Output:

VBA Regex Pattern Validation

Some Other useful Regex Patterns

  1. Password validation using Regex
  • Strong Password: It consists at least one small letter, one capital letter, one symbol, and one number, and it should be 8 chars long.

Regex Syntax:

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})
  • Medium password: It consists one capital, one small letter, and one numeric field, and total 6 chars long.

Regex Syntax:

^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{6,}))
  • Simple password: It takes at least one alphabet, and one numeric field [alphanumeric], and the total length should be 5 characters long.

Regex Syntax:

^((?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,}))
  • RegEx Pattern for Date format : DD/mm/yyyy

Regex Syntax:

^((0[1-9]|[1-9]|[12][0-9]|3[0-1])\/(0[1-9]|[1-9]|1[0-2])\/([12]\d{3}))
  • Regex Pattern for NL Postal Code

Regex Syntax:

\d{4}[ ]*([aA-zZ]{2})$
  • Regex Pattern for US Postal Code format

Regex Syntax:

^\d{5}(?:[-\s]\d{4})?$
  • RegEx Pattern for Website URL
(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})

Related Topics

Excel VBA Weekday Function

Excel VBA Weekday Function: The TimeValue function in VBA returns an integer (1 to 7), signifying the day of the week for the specified date. Syntax Weekday (Date, [FirstDayOfWeek]) Parameter Date (required) – This parameter...

2 minutes read.

Excel VBA Join Function

Excel VBA Join Function: The Join function in VBA is used to join an array of substrings and return them all as a single string. Syntax Join (SourceArray, [Delimiter]) Parameter SourceArray (required) – This parameter...

1 minute read.

Excel VBA Asc Function

VBA Asc Function: The Asc function in VBA returns an integer showing the character code for the first character of a given string. Syntax Asc (String) Parameter String (required) – This parameter represents the text...

1 minute read.

VBA Pivot Table

What is a Pivot Table? One of the most powerful features of Excel VBA is the Pivot Table. A pivot table is a VBA tool that is used to create summary...

3 minutes read.

Excel VBA IsError Function

VBA IsError Function: The IsError function in VBA returns a Boolean value showing whether the specified Expression represents an error or not. Syntax IsError (Expression) Parameter Expression (required)- This parameter represents the variant that you...

1 minute read.

VBA ActiveCell Property

What is the ActiveCell Property? The active cell signifies the active selected cell in the current worksheet. The Active property acts as a reference point and is used to move the cell cursor...

5 minutes read.

Excel VBA GoTo Statement

GoTo Statement he GoTo statement branches unconditionally to a specified line in a procedure. It is used to transfer the program control to a new statement, which is headed by a label. It sends...

2 minutes read.

Excel VBA- Pivot Table Fields

VBA- Pivot Table Fields: The Pivot Fields collection contains all the fields from the data source, including any calculated fields. The main aspect of adding a field is its Position...

4 minutes read.

Procedures in VBA

Procedures in VBA A procedure is a block of statements or units of computer code that performs some action. It is enclosed with a declaration statement, and its primary purpose is to carry out...

3 minutes read.

UserForm and its Properties Excel VBA

UserForm and its Properties Userform has certain properties that can be viewed as category wise (based on appearance, behavior, font) or in an alphabetic manner. The property window is used to set or...

11 minutes read.

Excel VBA Right Function

VBA Right Function: The Right function in VBA returns a substring from the end of the given string. Syntax Right (Str, Length) Parameter Str (required) – This parameter represents the string from which you want to...

1 minute read.

VBA Screen Updating

What is VBA Screen Updating property? Screen Updating is a VBA property which is used to display the output generation while running the code. If this property is enabled, we could see...

6 minutes read.

VBA Global Variable

What is Global Variable? The Global Variables in VBA refers to the variables declared before the start of any macro. They are defined outside the functions and are used by all the functions or...

6 minutes read.

Excel VBA DatePart Function

The DatePart function in VBA returns a part (day, month, week, etc.) for the specified date and/or time. Syntax DatePart (Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear]) Parameter Interval (required) – This parameter represents a string specifying the interval to be used. It can...

2 minutes read.

Excel VBA Fix Function

VBA Fix Function: The Fix function in VBA truncates the given number to an integer and returns the rounded off integer number. This function both positive and negative numbers to zero. Syntax Fix...

1 minute read.

Excel VBA DateSerial Function

The DateSerial function in VBA returns a Date from a supplied year, month, and day number. Syntax DateSerial (Year, Month, Day) Parameter Year (required) – This parameter represents an integer signifying the year. Month (required) – This parameter...

2 minutes read.

Excel VBA Error Handling

What is Errors and Types of Error? Errors are conditions that resist the flow of the program or enables a problem while running any programming. There are three types of errors in VBA...

5 minutes read.

CodeIgniter Architecture

Here we will understand the architecture and working of the CodeIgniter application, which helps you to elaborate all steps in simple ways. As the above image represents that whenever a request comes from the...

2 minutes read.

Excel VBA Tutorial

What is VBA? Introduction to Excel VBA: Visual Basic for Applications (VBA) is a programming language developed by Microsoft to automate operations in applications, such as Excel, Word, PowerPoint, etc. It...

5 minutes read.

Debugging in Excel VBA

Debugging in VBA: Debugging is a technique used to fix errors in programming languages. In Excel VBA, we have different ways by which you can identify the error in the...

2 minutes read.