Re: VBA to Extract text with certain pattern from a string within a single cell
Quote from bryce;789740here you go. I changed the pattern a little. Instead of looking for 4 numbers and 1 character at the end of the part number I simply look for 5 numbers or letters. There is also no need to remove the item No. xxx or the numerical listing in front of the part number. This returns only the part number
CodeDisplay MoreSub stringSearch() Dim ws As Worksheet Dim lastRow As Long, x As Long Dim matches As Variant, match As Variant Dim Reg_Exp As Object Set Reg_Exp = CreateObject("vbscript.regexp") With Reg_Exp .Pattern = "\d{2,3}-\D{1,2}-\d{3}-\w{5}" .Global = True End With ' ###-TT-###-####T <-----This is what you say your pattern looks like ' \d{2,3} = Match any number 0-9, 2 to 3 times. You indicate that the first part of the string will have 3 numbers but your sample shows it may also have 2 ' \D{1,2} = Match any non-number 1 to 2 times. Your sample indicates that 2 letters will follow 3 numbers but your sample indicates that there may be 1 or 2 letters ' \d{3} = Match any number 0-9, 2 to 3 times. Didn't see any variation in your claimed pattern and sample ' \w{5} = Match 5 numbers or non-numbers. This is the last part of your pattern. This accomodates either 5 numbers, letters oir a combination. As long as the last section of the part number is 5 characters long this will work Set ws = Sheet1 lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row For x = 1 To lastRow Set matches = Reg_Exp.Execute(CStr(ws.Range("A" & x).Value)) If matches.Count > 0 Then For Each match In matches ws.Range("B" & ws.Range("B" & Rows.Count).End(xlUp).Offset(1).Row).Value = match.Value Next match End If Next x End Sub
Dude. This is impressive!The amount of code is way less than I have in mind when I plan to do it before. Thanks!