Excel VBA: Returning a String found in a Regex Pattern

Converemon

New Member
Joined
May 23, 2014
Messages
15
I have a string and a pattern. If a substring of the string is found in the pattern, the string is no longer valid. I would like to return a message stating which substring was found in the pattern. I appreciate any help.

String: K22+L09+P88+Q12+J56
Pattern: (N75|X02|A21|U67|L09|...)
Output Should Be: "J56 is an invalid code. Blah-Blah"

Code to test string against pattern:
Code:
Function Test_OPC(sCode, sPattern) As Boolean
Dim RegX As Object
Dim RegMC
Set objRegX = CreateObject("VBScript.RegExp")
With objRegX
    .Pattern = sPattern
    If .Test(sCode) Then
        Set RegMC = .Execute(sCode)
        Test_OPC = True
    Else
        Test_OPC = False
    End If
End With
End Function

My only problem is returning which code was found in the pattern. I am willing to consider different approaches as well.
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
I'm not sure why you would want to return J56, when you say you wan to return the one that matched. This is assuming there will only be one match:

Code:
Function PatternString(sCode As String, sPattern As String) As String
With CreateObject("vbscript.regexp")
    .Pattern = sPattern
    If .test(sCode) Then PatternString = .Execute(sCode)(0)
End With
End Function
Excel Workbook
AB
1K22+L09+P88+Q12+J56L09
Sheet1
 
Upvote 0
I really appreciate your time. Apologies for putting down the wrong code. I was originally using J56 but I changed it. Thank you for your help; you gave me exactly what I needed.
 
Upvote 0

Forum statistics

Threads
1,216,312
Messages
6,130,009
Members
449,550
Latest member
8073662045

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