×

VBA Regex

What is a Regex?

Regex stands for Regular Expression is basically a pattern matching strings within another string. They are supported in many languages, including .net, C++, Python, etc. They are necessarily a sequence of characters that act as a search algorithm and matches the pattern. Excel offers quite a bit of text functions, but none of them can compare with regular expressions. Regular Expressions are often used to are used to validate website input or user input matches with the data, search for word patterns in large strings/texts with a specific pattern.

Regex Expressions

The Regex expressions are evaluated through matching expressions and Quantifiers.

Matching Expression

SyntaxDescriptionExampleMatch
.It signifies all the characters except vbNewLine (newline).d.ndan, don, d@n, dwn
[character]It matches the given characters present in between the brackets [ ].[dn]It Would only match “d” or “n” in don
[^character]It is used to match the characters that are not being one of the provided between brackets [ ][^dn]It would only match “o” in “don”
[start-end]It matches any character belonging to the character range specified between brackets [ ][1-5]It would match “1” and “5” in “815”
\w It represents the word character including alphabets, modifiers, digits, punctuation and connectors.\wIt would match “c” in “@@#,c.”
\WIt represents any non-word character.\WIt would match “#” in “bb#bb”
\sIt signifies any white space character.\sIt will match ” ” in “Hi This is”
        \SIt represents any non-white space character\SIt would match “K” and “h” in “K h”
\d
It represents any decimal digit in between 0-9.  

\d  
It would match “8” in “j8h”
\DIt represents all characters except non-decimal digit.\DIt would match j in “4723p”
\
This expression is followed by any special character – escapes special characters.  

\.  
It would match “.” in “889.paQ”
\tThis parameter represents tab.\tIt would match a tab character
\rThis expression represents the Tab value (vbTab)\r
It would match a carriage return (vbCr)  
\nThis expression represents the Carriage and returns a new line (vbNewLine).\nIt would match a new line

Quantifiers

The quantifiers are used to specify the number of times the user wants to match the pattern against the string.

SyntaxDescription
*It signifies zero or more of values. It matches as many as values as possible.
+It represents one or more of values and matches as many as possible values.
?If it is zero or once it matches as many as possible
{n}It repeats the values “n” many times
{n,}It repeats the values at least “n” times
{n,m}Between “n” and “m” times (GREEDY)
*?Zero or more of (non-GREEDY). Matches as few as possible
+?One or more of (non-GREEDY). Matches as few as possible
??It signifies zero or once and matches as few as possible
{n,}?At least “n” times (non-GREEDY). Matches as few as possible
{n,m}?It represents values between “n” and “m” times and matches as few as possible values.  

Regular Expression Language

The Regular Expression object has the following four properties:

  • Pattern – It represents the pattern with regex expression that you want to match against.
  • IgnoreCase – This property will ignore the letter case (upper case/ lower case). It will only match the pattern in the string irrespective of its case.
  • Global – This property finds all the possible matches in the input string. If it is set to Boolean false, it only matches the first found pattern.
  • MultiLine – This property helps to match the pattern across line breaks.

The Regular Expression object has the following 3 operations:

  1. Test (string) – This operation returns a Boolean True if the pattern gets matched against the given string
  2. Replace (search-string, replace-string) – This operation replaces the occurrences of the pattern in search-string with replace-string
  3. Execute (search-string) – This operations returns all matches of the pattern computed against the search-string.

Steps to create Regex in VBA

The steps to create Regex in VBA are as follows:

Step 1: Open the Visual Basic Editor by pressing Alt + F11. Go to Tools and select the References option to enable the Regex functionality.

Steps to create Regex in VBA

Step 2: The VBA references option list will appear to the VBA Project. Scroll down and select the “Microsoft VBScript Regular Expression 5.5” option.

Steps to create Regex in VBA

Step 3: Now click on OK button on the right side of the dialog box. Now, we can access this Regex object in the VBA coding.

Steps to create Regex in VBA

Step 4: Set the object for Regex variable.

Program:

Sub VBA_Regex_Program()
Dim stringVar As String
Dim regexVar As Object
‘Declaring the object for Regex
Set regexVar = New RegExp
Steps to create Regex in VBA

Step 5:  Define the regex pattern and methods as per the program’s demand. Here in the below program we have set a pattern for “A.C” so find all the possible matches that includes A.C (A, any character, c).

Program:

Sub VBA_Regex_Program()
Dim stringVar As String
Dim regexVar As Object
‘Declaring the object for Regex
Set regexVar = New RegExp
‘defining the methods
regexVar.Pattern = "A.C"
regexVar.Global = True
regexVar.IgnoreCase = IgnoreCase
stringVar = "HIABC-1289C-AVC-1A289C-ANC"
Steps to create Regex in VBA

Step 6: Setting the match for the regex variable.

Program:

Sub VBA_Regex_Program()
Dim stringVar As String
Dim regexVar As Object
‘Declaring the object for Regex
Set regexVar = New RegExp
‘defining the methods
regexVar.Pattern = "A.C"
regexVar.Global = True
regexVar.IgnoreCase = IgnoreCase
stringVar = "HIABC-1289C-AVC-1A289C-ANC"
‘setting the match value
Set theMatches = regexOne.Execute(stringOne)

Step 7: Running the foreach loop to find the match throughout the given string variable.
The entire scope of program is given below. Press F5 to run the output for the program.

Program:

Sub VBA_Regex_Program()
Dim stringVar As String
Dim regexVar As Object
‘Declaring the object for Regex
Set regexVar = New RegExp
‘defining the methods
regexVar.Pattern = "A.C"
regexVar.Global = True
regexVar.IgnoreCase = IgnoreCase
stringVar = "HIABC-1289C-AVC-1A289C-ANC"
‘setting the match value
Set theMatches = regexOne.Execute(stringVar)
For Each Match In theMatches
  Debug.Print Match.Value
Next
End Sub
VBA Regex

Output for the above program

You will get the output at the immediate window. Click on insert -> Immediate Window.

VBA Regex

Related Topics

Excel VBA String Function

The String function in VBA creates a String, consisting of several repeated characters. Syntax String (Number, Character) Parameter Number (required) – This parameter represents the number of characters in the returned String. Character (required) – This parameter...

1 minute read.

VBA Cell

What is VBA cell? Cells is one of the elements (workbook, worksheet, range) in Excel VBA, which refers to cells of the Excel worksheet.  In VBA, the cell is also a property...

5 minutes read.

Excel VBA INT Function

VBA INT Function: The INT function in VBA rounds the given supplied number down and returns an integer value. The positive numbers are rounded to zero, and the negative numbers are rounded away from zero. Syntax Int...

1 minute read.

VBA Object Required

What is Object Required Error? VBA Object Required is a run time error which occurs when the user does not define a valid object qualifier, or the assigned object doesn’t exist in the...

6 minutes read.

VBA Regex

What is a Regex? Regex stands for Regular Expression is basically a pattern matching strings within another string. They are supported in many languages, including .net, C++, Python, etc. They are...

5 minutes read.

Excel VBA IsNumeric Function

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

1 minute read.

Excel VBA InStr Function

VBA InStr Function The InStr function in VBA searches for a substring inside the given string. It returns the position of a substring within a string, as an integer if the substring is found...

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.

Excel VBA DateDiff Function

The DateDiff function in VBA returns a Long data value representing the number of intervals between two specified dates/times where the type of interval is supplied by the user. Syntax DateDiff (Interval, Date1, Date2, [FirstDayOfWeek], [FirstWeekOfYear]) Parameter Interval (required)...

2 minutes read.

If ElseIf ElseIf Statement or Nested If statement in VBA

VBA Excel: If … ElseIf … ElseIf Statement or Nested If statement This function enables you to check multiple conditions and, based on that, then run one of the statement blocks present. If...

2 minutes read.

Excel VBA Rnd Function

VBA Rnd Function: The Rnd function in VBA returns a random number that is greater than or equal to (>=) 0 and is less than (<) 1. Syntax Rnd ([Number]) Parameter Number (optional) –This...

1 minute read.

Scope in Visual Basics

Definition of Scope The scope of any programming language implies the area of code where the variables will be identified, accessed, and used. Every variable has a scope associated with it. The scope of...

4 minutes read.

Excel VBA InStrRev Function

VBA InStrRev Function: The InStrRev function in Excel VBA returns an integer representing the position of a substring within the specified string if the substring is fount else it returns...

2 minutes read.

Excel VBA MessageBox

Message Box The MsgBox in Excel VBA is a dialog box used to inform the users of your program by showing a custom message or get some necessary inputs such as Yes/No or...

4 minutes 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 StrReverse Function

The StrReverse function returns a String after reversing the given String. Syntax StrReverse (Expression) Parameter Expression (required) – This parameter represents the String that you want to reverse. Return This function returns a String after reversing the given String. Example...

1 minute read.

VBA Pivot Table Grouping

VBA- Pivot Table Grouping For an instance, if in our pivot table, we have 11 different age groups from 20 to 30 -  but there might be a possibility that we...

2 minutes read.

VBA Subscript out of Range

What is Subscript out of Range? The VBA Subscript out of Range error (which is also called as Run-Time Error 9) mostly triggers when the user selects any cell, sheet, or workbook which does...

5 minutes read.

Excel VBA LTrim Function

VBA LTrim Function: The LTrim function in VBA removes the leading spaces from a supplied text string. Syntax LTrim (String) Parameter String (required) - This parameter represents he text string that you want to remove...

1 minute read.

VBA Charts

What is a Chart? A chart is used to visually show numbers or data in a spreadsheet (or spread over multiple spreadsheets) so that the end-user can look at the chart...

3 minutes read.