In the below I am trying to create new tabs in a worksheet based of a column 3 in MainSheet (if they dont exist already). I think the below should do that, but I can not figure out how to group lines in MainSheet based on a matching number prefix.... that is 210422-C is the cell and the 2104 once extracted matches the line below it. So those two lines would be copied to a new tab called 04-21 (reverse of the extracted prefix separated with a - after the second digit). 210505-C is the cell and the 2105 once extracted matches the line below it. So those two lines would be copied to a new tab called 05-21 (reverse of the extracted prefix separated with a - after the second digit). There wont always be two rows that match and there are multiple columns in each line. Thank you :).
MainSheet
header row
12 aaaa 210422-C bbb
12 abaa 210429-C bbb
12 caaa 210505-C bbb
12 dddd 210511-C bbb
Desired
04-21
header row
12 aaaa 210422-C bbb
12 abaa 210429-C bbb
05-21
header row
12 caaa 210505-C bbb
12 dddd 210511-C bbb
VBA
Private Sub
CommandButton1_Click()
Dim MainSheet As Worksheet
Dim NewSheet As Worksheet
Dim myBook As Workbook
Dim lastRow As Long
Dim i As Long
Dim namesColumn
'Define workbook - here set as the active workbook
Set myBook = ActiveWorkbook
'Define worksheets - The sheets are named "MainSbeet"
Set masterSheet =
myBook.Worksheets("MainSheet")
'Define which column in your master tab to search
namesColumn = 3
'Find the last row of the sheets list
lastRow = MainSheet.Cells(MainSheet.Rows.Count, namesColumn).End(xlUp).Row
'Cycle through the list - Assuming header row and starts in column "A" from the 2nd row
For i = 2 To lastRow
With myBook
'Define new sheet
Set NewSheet = .Worksheets.Add(After:=.Worksheets("MainSheet"))
End With
'Find name of the tab and naming the tab
tabName = masterSheet.Cells(i, namesColumn)
NewSheet.Name = tabName
'Copy from MainSheet MainSheet.ActiveCell.EntireRow.Select.Copy _
Destination:=NewSheet.ActiveCell.EntireRow.Select
'Paste in e.g. cell A1 i.e. (1,1) the tab name
NewSheet.Cells(1, 1).Value = tabName
'Only add sheet if it doesn't exist already and the name is longer than zero characters
If (Sheet_Exists(NewSheet) = False) And (NewSheet <> "") Then
Worksheets.Add().Name = NewSheet
End If
Next i
End Sub