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
Country Product name (Optional subname) Number CUR? That is what your regex does now, also ensuring there is 1 word char after the first whitespace matched. See your regex demo. Your requirements are somewhat different since you say you need to get the substring between a 5- and 6-digit number. What are the actual requirements?Trim()the value obtained and you are done.Dim regEx As New RegExp, but I get an error onAs New RegExp. This doesn't work.