Excel VBA RegEx formula

wheelsguy

New Member
Joined
Sep 23, 2013
Messages
7
Good morning.

I am new to Regular Expressions, and I am trying to validate a number like 012345-1234. I have the following:

Code:
Public Function ValidNumber(ByVal strNumber As String) As Boolean
    With CreateObject("VBScript.RegExp")
        .IgnoreCase = True
        .Global = True
        .Pattern = "^([0-9][0-9][0-9][0-9][0-9][0-9])-([0-9][0-9][0-9][0-9])$"
        ValidNumber = .Test(strNumber)
    End With
End Function

My code works, but I was hoping there was a better (shorter experession) way where it could be more recursive.

Thank you for looking, WHEELS
 
Thanks Rick. I haven't had a chance to test it yet, but it looks pretty clean and powerful. It resembles SQL (slightly). What would this techinque be called, and how would it be utilized to replace Regular Expressions for more complex validations?

It is plain VBA coding... Like is an operator (the same as =, >, etc) which compares the text string on the left with a patterned string on the right and returns a simple True or False result. It is not a replacement for RegExp, but it can do a lot of helpful things which help to avoid having to call up the heavy machinery of a RegExp engine. Here is a link to the help files for the Like operator (it is marked for Office 2010, but Like has not changed since its VBA version 6 was introduced into Excel, so you can use it for whatever version of Excel you are running).
 
Upvote 0

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().

Forum statistics

Threads
1,216,075
Messages
6,128,659
Members
449,462
Latest member
Chislobog

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top