Link to home
Start Free TrialLog in
Avatar of kbay808
kbay808Flag for United States of America

asked on

How do I fix my macro to search for a pattern within a string in excel?

I’m trying to create a macro to find the below examples from a string.
Fixed characters
????-AA*-BB*-*-*
ABCD-AAN12-BB3-AG3N5-XYZ123
GKME-AAJK5456-BB36G7-AN5-NJW123YUI

Function MatchSearch (strToSearch)
Set oRegEx = CreateObject("vbscript.regexp")
oRegEx.Global = True
oRegEx.IgnoreCase = True
oRegEx.Pattern = "[A-Z]{4,}-AA*-BB*-*-*"
Set RegExMatches = oRegEx.Execute(strToSearch)
If RegExMatches.Count = 1 Then
    MatchSearch = RegExMatches.Item(0)
Else
    MatchSearch = ""
End If
End Function

Open in new window

Avatar of Michael Fowler
Michael Fowler
Flag of Australia image

This should work for you

Function MatchSearch(strToSearch) As String
    Set regex = CreateObject("vbscript.regexp")
    
    With regex
        .Global = True
        .IgnoreCase = True
        .Pattern = "[A-Z]{4}-AA.*-BB.*-.*-.*"
    End With
        
    Set RegExMatches = regex.Execute(strToSearch)
    
    If RegExMatches.Count = 1 Then
        MatchSearch = RegExMatches.Item(0)
    Else
        MatchSearch = ""
    End If
    
End Function

Open in new window


You were just missing the "." to signify any character
ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In addition to the AA and BB, these two patterns match the other sections more closely than the wildcard character.
[A-Z]{4}-AA\w{3,6}-BB\w{1,4}-\w{3,5}-\w{6,9}

Open in new window


or
[A-Z]{4,}-AA\w{3,6}-BB\w{1,4}-[A-Z]{2}\w{1,3}-[A-Z]{3}\w{3,6}

Open in new window

Avatar of kbay808

ASKER

That worked great!!!  Thank you very much.