Friday, August 24, 2018

How to get match value of regex in VBA

I'm new to VBA and I need to get the value of a RegEx match and copy its value into another cell.



The string I need to match against will always be in cell E1 and will always follow this type of pattern:



CompanyName/12345 Country Product name (Optional subname) Number CUR 123456



I need everything inbetween the 5 and 6 digit numbers, so the following regex gets what I need:



\s\w.*\s


(Space, one or more word characters, space)



I just don't know how to get the VALUE of this match. I see a lot of RegEx.Replace methods on SO but I can't seem to find something that gets me the match value.




Here is my code (using RegEx.Replace):



Sub GetProdID()
Dim RegEx As Object
Dim myCell As Range
Set RegEx = CreateObject("VBScript.RegExp")
On Error Resume Next
RegEx.Pattern = "\s\w.*\s"


ActiveWorkseet.Range("E1").Value = RegEx.Replace(ActiveWorkseet.Range("E1").Value, "")
Next
End Sub


How do I just get the value of the match?
And how would I do this if the string I'm matching is always in one cell?



Update: The link provided in the comments led me to the right solution.
Here is the code edits, thanks to Wiktor Stribiżew for help




Sub GetProdID()
Dim myCell As Range
Dim Prod As String
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\s\w.*\s"

Set matches = regEx.Execute(Range("E1"))
Prod = Trim(matches(0))
Range("F1").Value = Prod

End Sub

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...