Macro extracting part of string

peter_sjogarde

Board Regular
Joined
Feb 13, 2012
Messages
56
I am trying to figure out how to keep only a part of a string. The part I want to keep is marked with capitals in the example below.

Example of cell contents:
[something between brackets, like this]something else, belonging to the, same occurrence, PART OF INTEREST;[a new occurrence]with, a string, like this, AND STRING OF INTEREST

So from this cell I want to keep or print in new column "PART OF INTEREST;AND STRING OF INTEREST"

I.e. the part between the last comma and the semicolon for each occurrence and the part after the last comma of the whole string


I do not want a function but rather a macro doing this and puts the result in a new column. I use this code to loop and remove the brackets:

Code:
   Dim x As Integer
   ' Set numrows = number of rows of data.
   NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count

   ActiveCell.Select

   For x = 1 To NumRows
      ActiveCell.Offset(1, 0).Select
      Selection.replace What:="
[*]", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
   Next
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.

Hi Jon

Another option is to do it without the submatch:

Code:
Sub Test()
Dim r As Range, rC As Range
 
Set r = Range("A1:A5")
With CreateObject("VBScript.RegExp")
    .Pattern = "[^;]+?,(?=[^;,]+(;|$))"
    .Global = True
    For Each rC In r
        If .Test(rC) Then rC.Offset(, 1) = .Replace(rC, "")
    Next rC
End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,889
Messages
6,175,223
Members
452,620
Latest member
dsubash

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top