{"id":14775,"date":"2018-09-05T22:18:49","date_gmt":"2018-09-05T22:18:49","guid":{"rendered":"http:\/\/learnexcelmacro.com\/wp\/?p=14775"},"modified":"2022-08-17T19:15:40","modified_gmt":"2022-08-17T19:15:40","slug":"regex-tester-in-excel-vba","status":"publish","type":"post","link":"https:\/\/vmlogger.com\/excel\/2018\/09\/regex-tester-in-excel-vba\/","title":{"rendered":"Regular Expression and its usage in Excel VBA"},"content":{"rendered":"
[et_pb_section fb_built=”1″ admin_label=”section” _builder_version=”4.17.6″ custom_padding=”0px|0px|0px|0px|true|true” da_disable_devices=”off|off|off” global_colors_info=”{}” da_is_popup=”off” da_exit_intent=”off” da_has_close=”on” da_alt_close=”off” da_dark_close=”off” da_not_modal=”on” da_is_singular=”off” da_with_loader=”off” da_has_shadow=”on”][et_pb_row admin_label=”row” _builder_version=”4.17.6″ background_size=”initial” background_position=”top_left” background_repeat=”repeat” custom_padding=”0px|0px|0px|0px|false|false” global_colors_info=”{}”][et_pb_column type=”4_4″ _builder_version=”4.16″ custom_padding=”|||” global_colors_info=”{}” custom_padding__hover=”|||”][et_pb_text _builder_version=”4.17.6″ _module_preset=”default” custom_padding=”0px|0px|0px|0px|false|false” global_colors_info=”{}”]Dear Reders,<\/p>\n
In this article, I am going to teach you What is Regular Expression (RegExp or RegEx)<\/strong>? and how RegEx is used in Excel VBA programming.<\/strong> You will also learn the usage of Regular Expressions in Excel VBA with some example VBA code. You can also find some simple regular expression patterns which are more often used. <\/a><\/p>\n \nRegEx is basically short form of Reg<\/strong>ular Ex<\/strong>pression. It is also called as RegExp<\/strong>. Regular Expression is a pattern string which is used as a search pattern. In other words – regular expressions can be imagined as a sequence of wildcard characters.<\/p>\n These are very useful in many ways…few of them are here…<\/strong><\/p>\n 1. Wild Search: <\/strong> You can search a specific types of string which follows a specific pattern rather than providing the exact word to search. <\/a><\/p>\n VBScript has a built-in support for RegEx – Regualr Expression. It is very simple to use. <\/p>\n To use this built-in feature, you can use early binding you need to add reference in your VBA project<\/a> – VBScript.RegExp <\/a><\/p>\n It provides basically three main methods: <\/a><\/p>\n – In this method, a match from a string is extracted based on defined mathcing pattern [RegEx Pattern]. This method returns an Object which holds all the matches as an Array format. To read all the matches found, you need to loop through the object returned as shown in the below code.<\/p>\n <\/a><\/p>\n \u2013 Using this method a character or string is searched based on a defined pattern, and once found it is replaced with a new character or string defined. It returns a new string with all the matched string replaced with provided string.<\/p>\n <\/a><\/p>\n – This is used to find whether a Regex pattern is matched in a given string. It returns True or False – based on match found or not found.<\/p>\n <\/a><\/p>\n Though as you must have already got an idea that this can be used in many ways in Excel VBA. Following function can extract and list all the emailds and telephone numbers written in a string. In place of string you can ofcourse pass the value from a cell and you can extract all the email ids and phone numbers from a cell and put them in another cell using loop. It is up to you how you want to use the extracted data.<\/p>\n For example – in Excel VBA form Text Box [txtEmailID – Name of the TextBox.] You can put the following code in any of the event where you want to trigger this validation.<\/p>\n In this example, I have put this code in TextBox Change Event<\/strong>. This is an example code. You can always change the RegEx pattern etc. according to your need. <\/a><\/p>\n I have listed some most frequently used RegEx. All the following examples are also listed in the Excel Sheet which you can download at the end of the article.<\/p>\n Here in this Excel Sheet, when you select a type then automatically a regular expression pattern and one example data will appear to validate – as shown in below gif file. Strong Password:<\/strong> at least one small letter, one capital letter, one symbol and one number and it should be 8 chars long<\/p>\n Medium password:<\/strong> One capital, one small letter and one numeric field and total 6 chars long<\/p>\n Simple password: [alphanumeric]<\/strong><\/h4>\n At least one alphabet and one numeric field and total 5 chars long<\/p>\n <\/a>[\/et_pb_text][et_pb_cta title=”Download this FREE Tool – RegEx validator” button_url=”\/excel\/wp-content\/downloads\/RegexValidator-v0.01.xlsm” button_text=”Download your FREE Workbook” _builder_version=”4.17.6″ _module_preset=”a50a16dd-d05f-4ea2-acab-1468d2e4010e” global_colors_info=”{}”]In the following Excel Regex validation tool, you can type your own Regular expression pattern and enter the data which you want to validate against the pattern. You will see the result immediately whether your input data is as per the pattern you provided. [\/et_pb_cta][et_pb_blurb title=”You may like reading them:” use_icon=”on” font_icon=”||fa||900″ _builder_version=”4.17.6″ _module_preset=”0249c68e-4de8-4f44-84ff-a9b1850785b6″ hover_enabled=”0″ global_colors_info=”{}” sticky_enabled=”0″]<\/p>\n [\/et_pb_blurb][\/et_pb_column][\/et_pb_row][\/et_pb_section]<\/p>\n<\/span>","protected":false},"excerpt":{"rendered":" Dear Reders, In this article, I am going to teach you What is Regular Expression (RegExp or RegEx)? and how RegEx is used in Excel VBA programming. You will also learn the usage of Regular Expressions in Excel VBA with some example VBA code. You can also find some simple regular expression patterns which are […]<\/p>\n","protected":false},"author":45,"featured_media":242567,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"on","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[1676,5204],"tags":[],"class_list":["post-14775","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-excel-tips","category-vba-programming"],"yoast_head":"\n
\nRefer to the following table to see what all the major topics going to be covered in this article.<\/p>\nIndex : Topics covered under this Article<\/h2>\n
1. What is Regex<\/a> <\/h4>\n
2. How to use RegEx in Excel VBA<\/a><\/h4>\n
3. VBA to validate a string against a RegEx pattern<\/a><\/h4>\n
4. VBA to Search based on a RegEx pattern<\/a><\/h4>\n
5. VBA to replace strings with specific string which matches with given RegEx pattern<\/a><\/h4>\n
6. Usage of RegEx in Excel VBA<\/a> <\/h4>\n
7. 13 most commonly used RegEx Patterns<\/a> <\/h4>\n
8. Regex Tester – Free Excel Tool Download<\/a><\/h4>\n
What is RegEx – Regular Expression ?<\/h1>\n
\n2. Validation:<\/strong> You can validate any input or output – if it has a specific pattern
\n3. Extraction: <\/strong> Extract specific kind of words or phrases which follows specific pattern.
\n….
\nTo know more about Regular Expressions, you can also read this Wiki page –<\/em> https:\/\/en.wikipedia.org\/wiki\/Regular_expression<\/a><\/p>\nHow to use RegEx in Excel VBA<\/h1>\n
\nor else you can create Object of type VBScript.RegExp before you use it.<\/p>\nMethods of VBScript.RegEx using in VBA<\/h1>\n
\n 1. <\/strong>.Execute<\/strong>
\n 2. <\/strong>.Replace<\/strong>
\n 3. <\/strong>.Test<\/strong><\/p>\n1# RegEx Execute Method in VBA<\/h2>\n
\n
\nFunction executeMethodRegEx(regPattern As String, regString As String)\n'***************************************************************\n' Example of Execute Method of RegEx\n' Function to retrieve all the matches\n' found in a given string which matches\n' the regex Pattern string\n' Note: Returns an object holding all the matches\n' found like an array.\n'***************************************************************\nDim rgx As Object\nSet rgx = CreateObject(\"VBScript.RegExp\")\nDim allMatches As Object\nWith rgx\n .Pattern = regPattern\n .Global = True\n .IgnoreCase = True\n .MultiLine = True\nEnd With\n\n' AllMatches object stores all the matches\n' returned by execute method of RegEx\nSet allMatches = rgx.Execute(regString)\n\n'Loop to read all the matches found\nFor Each Item In allMatches\n Debug.Print Item.Value\nNext\nEnd Function\n<\/code>\n<\/pre>\n
2# RegEx Replace Method in VBA<\/h2>\n
\n
\nFunction rePlaceMethodRegEx(regPattern As String, origString As String)\n'***************************************************************\n' Example of Replace Method of RegEx\n' Function to replace all the matches\n' found in a given string which matches\n' the regex Pattern - with a given string\n' Note: It return a new string where all the matches\n' are replace with the provided string\n'***************************************************************\nDim rgx As Object\nSet rgx = CreateObject(\"VBScript.RegExp\")\n\nWith rgx\n .Pattern = regPattern\n .Global = True\n .IgnoreCase = True\n .MultiLine = True\nEnd With\n\n' Replace method returns a new string\n' with all the matched string replaced\n' with your provided string\nDebug.Print rgx.Replace(origString, \"***abc@email.com***\")\nEnd Function\n<\/code>\n<\/pre>\n
3# RegEx Test Method in VBA<\/h2>\n
\n
\nFunction testMethodRegEx(regPattern As String, regString As String) As Boolean\n'***************************************************************\n' Example of Test Method of RegEx\n' Function to check if Provided String\n' matches with the regex pattern provided\n' Note: It return as boolean - True or False\n'***************************************************************\n Dim rgx As Object\n Set rgx = CreateObject(\"VBScript.RegExp\")\n With rgx\n .Global = True\n .MultiLine = True\n .IgnoreCase = False\n .Pattern = regPattern\n End With\n ' Function returns a boolean - true\/false\n ' based on match or no match\n testMethodRegEx = rgx.test(regString)\nEnd Function\n<\/code>\n<\/pre>\n
Usage of RegEx in Excel VBA<\/h1>\n
\nHere are some quite obvious usage of RegEx in Excel VBA:<\/p>\nUsage 1# Extract and List all the Email IDs and Phone Numbers from a Cell Text<\/h2>\n
\n
\nFunction listEmailIDsAndPhoneNumbers(regString As String)\n'***************************************************************\n' Combined two patterns with pipe sign (|) = OR\n' Pattern1 = To validate Telephone number with Country code\n' Pattern2 = Email ID\n' This function returns the string if any one\n' of the pattern matches\n'***************************************************************\nDim rgx As Object\nSet rgx = CreateObject(\"VBScript.RegExp\")\nDim allMatches As Object\nDim emailRegPattern As String\nDim phoneNumberRegPattern As String\nemailRegPattern = \"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.])\"\nphoneNumberRegPattern = \"([+]{1}[0-9]{2}[-]{1}[1-9]{1}[0-9]{9})\"\n\nWith rgx\n .Pattern = phoneNumberRegPattern & \"|\" & emailRegPattern\n .Global = True\n .IgnoreCase = True\n .MultiLine = True\nEnd With\n\n' All emailIDs adn telephone numbers would be\n' listed in this Object\nSet allMatches = rgx.Execute(regString)\n\n'Loop to read all the matches found\nFor Each Item In allMatches\n Debug.Print Item.Value\nNext\nEnd Function\n<\/code>\n<\/pre>\n
Usage 2# Restrict user to type a valid format of email ID in your Excel Form<\/h2>\n
\nAs soon as you type anything in the textbox, it will start validating the text typed in the TextBox. As soon as entry is correct as per the RegEx defined, textbox back color will change to green, till then it will remain Red.<\/p>\n\n
\nPrivate Sub txtEmailID_Change()\n If Not (testMethodRegEx(\"^([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.])\", txtEmailID.Text)) Then\n txtEmailID.BackColor = RGB(255, 0, 0)\n Else\n txtEmailID.BackColor = RGB(0, 255, 0)\n End If\nEnd Sub\n<\/code>\n<\/pre>\n
Usage 3# Replace all the email IDs and Phone Numbers with a dummy one in excel Sheet<\/h2>\n
\nIn following example, function takes a string as input and there are two patterns defined – 1. Telephone Number 2. Email ID. Based on these two regEx pattern, function will find the matched text and replace them with corresponding dummy values, you provide. Like Telephone number = +11-1111111111 or email ID as xyz@email.com etc. <\/p>\n\n
\n\nFunction maskEmailIDsAndPhoneNumbers(origString As String) As String\n'***************************************************************\n' Combined two patterns with pipe sign (|) = OR\n' Pattern1 = To validate Telephone number with Country code\n' Pattern2 = Email ID\n' This function returns the string if any one\n' of the pattern matches\n'***************************************************************\nDim rgx As Object\nSet rgx = CreateObject(\"VBScript.RegExp\")\nDim allMatches As Object\nDim emailRegPattern As String\nDim phoneNumberRegPattern As String\nemailRegPattern = \"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.])\"\nphoneNumberRegPattern = \"([+]{1}[0-9]{2}[-]{1}[1-9]{1}[0-9]{9})\"\n\nWith rgx\n .Pattern = phoneNumberRegPattern\n .Global = True\n .IgnoreCase = True\n .MultiLine = True\n origString = .Replace(origString, \"+11-111111111\")\nEnd With\n\nWith rgx\n .Pattern = emailRegPattern\n .Global = True\n .IgnoreCase = True\n .MultiLine = True\n origString = .Replace(origString, \"xyz@email.com\")\nEnd With\nSet rgx = Nothing\n' return the masked string\nmaskEmailIDsAndPhoneNumbers = origString\n\nEnd Function\n<\/code>\n<\/pre>\n
13 most commonly used RegEx Patterns:<\/h1>\n
\n<\/p>\n1. Email Validation RegEx<\/h4>\n
^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$<\/code><\/pre>\n
2. Password validation:<\/h4>\n
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})<\/code><\/pre>\n
^((?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{6,}))<\/code><\/pre>\n
^((?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,}))<\/code><\/pre>\n
4. RegEx Pattern for Alphanumeric Only<\/h4>\n
^((?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,}))<\/code><\/pre>\n
5. RegEx Pattern for Website URL<\/h4>\n
(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,})<\/code><\/pre>\n
6. RegEx Pattern for Positive numbers<\/h4>\n
^([+]?\\d+([.]\\d+))<\/code><\/pre>\n
7. RegEx Pattern for Negative numbers<\/h4>\n
^(\\-\\d+([.]?\\d+))<\/code><\/pre>\n
8. RegEx Pattern for 10 digit telephone number [not starting with Zero]<\/h4>\n
[1-9]{1}[0-9]{9}$<\/code><\/pre>\n
9. RegEx Pattern for Phone with a country code format<\/h4>\n
[+]{1}[0-9]{2}[-]{1}[1-9]{1}[0-9]{9}$<\/code><\/pre>\n
10. RegEx Pattern for Year between 1900 and 2018<\/h4>\n
(19[0-9]{2}|200[0-9]{1}|201[0-8]{1})$<\/code><\/pre>\n
11. RegEx Pattern for Date format : DD\/mm\/yyyy<\/h4>\n
^((0[1-9]|[1-9]|[12][0-9]|3[0-1])\\\/(0[1-9]|[1-9]|1[0-2])\\\/([12]\\d{3}))<\/code><\/pre>\n
12. RegEx Pattern for NL Postal Code<\/h4>\n
\\d{4}[ ]*([aA-zZ]{2})$<\/code><\/pre>\n
13. RegEx Pattern for US Postal Code format<\/h4>\n
^\\d{5}(?:[-\\s]\\d{4})?$<\/code><\/pre>\n
\n