×

VBA VBScript Regex Methods Regex

VBA VBScript Regex Methods Regex

The VBA Regex supports 3 methods which are as follows:

  1. Execute
  2. Replace
  3. Text
  1. Execute

The execute method is used to extract a match from the given based on the defined matching Regex pattern. It returns an Object which retains all the matches, unlike an Array.

In the below program we have created a Function to collect all the matches found in the given string  which will match the regex Pattern string and will return an object holding all the matches found in the string (unlike an array). At last, we have looped through the returned object to read all the matches found.

Syntax

Execute (String value)

Program:

Function VBA_Regex_executeMethod(regexVar As String, stringVar As String)
'***************************************************************
' Example for Execute Method of Regular Expression
'***************************************************************
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
Dim matchedObj As Object
With regex
    .Pattern = regexVar
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' The matchesObj object will store all the matches as
' returned by execute method of RegEx
Set matchedObj = rgx.Execute(stringVar)
'Loop to read all the matches found
For Each Item In allMatches
    Debug.Print Item.Value
Next
End Function
VBA VBScript Regex Methods Regex

2. Replace

The Replace method is used to search a character or string based on a defined pattern, and if the pattern is found, it is replaced with a new string or character as defined by the user (i.e the replacement string takes the place of each matched string). If the regex pattern is not matched with the string, the string remains unchanged. This method returns a new string with all the matched string replaced with provided string and replaces all strings that match a regular expression pattern with a specified replacement string.

In the below program, we have created a Function to replace all the matches found in each string, which matches the regex Pattern - with a given string. This program will return a new string where all the matches are replaced with the given string.

Syntax

Replace (string input, string replacement)

Program:

Function VBA_Regex_ReplaceMethod(regexVar As String, stringVar As String)
'***************************************************************
' Example of Replace Method of Regular Expression
'***************************************************************
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
'DEefining the regex properties
With regex
    .Pattern = regexVar
    .Global = True
    .IgnoreCase = True
    .MultiLine = True
End With
' This method will return a string wherein
' all the matched string will be replaced
' with the given string
Debug.Print regex.Replace(stringVar, "***vb@***tutori@ls***")
End Function
VBA VBScript Regex Methods Regex

3. Test Method

This method is used to find whether a Regex pattern is matched in a given string. This method returns a Boolean value True if the match is found else it returns a Boolean False.

In the below example, we have created a function to check if the specified String matches with the given regex pattern and return Boolean - True or False based on the match found result.

Syntax

Test (String value)

Program:

Function VBA_Regex_TestMethod(regexVar As String, stringVar As String) As Boolean
'***************************************************************
' Example of Test Method of Regular Expression
'***************************************************************
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Pattern = regexVar
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
    End With
    ' The test metho returns a boolean true if the match has found
    ' else it returs Boolean False for no match
    testMethodRegEx = regex.test(stringVar)
End Function
VBA VBScript Regex Methods Regex

Related Topics

Basics of Userform

A User Form is a built-in customized dialog box that fetches data from the user through a user-friendly dialog box or window that makes up part of an application's user interface. It...

9 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.

Excel VBA CDbl Function

VBA CDbl Function: The CDbl function in VBA converts an expression into a Double data type. Syntax CDbl (Expression) Parameter Expression (required) - This parameter represents the expression that that you want to convert to...

1 minute read.

Excel VBA Round Function

VBA Round Function: The Round function in VBA rounds a number to a specified number of decimal places and returns the number. Syntax Round (Number, [NumDigitsAfterDecimal]) Parameter Number (required) –This parameter represents a numeric value one wants...

1 minute read.

How to save Macro Workbook?

Saving Macro Workbook Default Excel File Extension The default excel file extension is “.xlsx”. But the standard file extension “.xlsx” cannot contains macros. So, the workbook contains macro when save din.xlsx file, all VBA...

1 minute read.

Excel VBA Day Function

The function Day in VBA returns the day number (from 1 to 31) for the given date value. Syntax Day (Date) Parameter Date (required) – This parameter represents the date. Return This function returns the day...

1 minute read.

Excel VBA Mid Function

VBA Mid Function: The Mid function in VBA returns a substring from within a supplied string. Syntax Mid (Str, Start, [Length]) Parameter Str (required) -This parameter represents a string from which you want to extract the substring. Start...

1 minute 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 ListBox

What is a ListBox? ListBox refers to a permanently displayed control (usually box-shaped) which contains a list of objects (or attribute, or elements) from which the user can select single or multiple attributes....

8 minutes read.

VBA Updating Pivot Table

VBA- Updating Pivot Table The pivot table is an important feature to explore, summarize, and interpret the bulk amount of data. It helps data evaluating, reviewing, as well as making useful...

3 minutes read.

Excel VBA Len Function

VBA Len Function: The Len function in VBA returns the number of characters in a supplied string or the number of bytes required to store a supplied variable. Syntax Len (Expression) Parameter Expression (required)-...

1 minute read.

Excel VBA: Select … Case Statement

Select … Case Statement When a group of statements is executed, depending upon the value of an Expression, then Switch Case is used.  If you have several conditions to check, then the If condition...

4 minutes read.

Excel VBA FormatDateTime Function

VBA FormatDateTime Function: The FormatDateTime function in VBA returns the result as a string after applying a date and/or time format to the supplied expression. Syntax FormatDateTime (Expression, [NamedFormat]) Parameter Expression (specified) – This parameter...

2 minutes read.

Excel VBA InputBox

Input Box The InputBox function in VBA is used to prompt the users to enter values. The user can click either the OK button or can choose the CANCEL button. If the user clicks...

3 minutes read.

Excel VBA: DO WHILE….Loop

DO WHILE….Loop The “Do While” Loop is the same, unlike the FOR statement, just that it will keep on looping till the specified condition is true. It is used when we want to...

3 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 Hour Function

The hour function in VBA returns the hour element for the specified time. Syntax Hour (Time) Parameter Time (required) – This parameter represents the time. Return This function returns the hour element for the specified time. Example 1 Sub HourFunction_Example1() ...

1 minute read.

Excel VBA While wend Loop

WHILE wend loop is used when the user is not sure how many times they want to execute the VBA code within the program. With a WHILE loop, the loop body may...

3 minutes read.

Excel VBA UBound Function

Excel VBA UBound Function: The UBound function in VBA returns the highest subscript for the specified dimension in the given array. Syntax UBound (ArrayName, [Dimension]) Parameter ArrayName (required) – This parameter represents an array for which...

1 minute read.

VBA Type Mismatch Error

What is a Type Mismatch Error? VBA Type Mismatch Error is a run time error in excel, which often occurs when the data types contained in a VBA code are not matched...

3 minutes read.