1

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 
8
  • Do you want to get everything between the first and last spaces? 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? Commented Sep 15, 2017 at 7:32
  • Ok, you can figure that out yourself. Your answer is here. Commented Sep 15, 2017 at 7:37
  • Thank you for the follow up. I would need Everything within those spaces. So I would need "Country Product name (Optional subname) Number CUR". Basically, I need to strip out everything in the middle of the 5 digit and 6 digit numbers. Commented Sep 15, 2017 at 7:38
  • What you say and what you try is different. So, if you just need to know how to obtain the match value, see this answer. Then Trim() the value obtained and you are done. Commented Sep 15, 2017 at 7:40
  • The problem with these examples is they always se the Regex as Dim regEx As New RegExp, but I get an error on As New RegExp. This doesn't work. Commented Sep 15, 2017 at 8:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.