I am not sure if I am performing this operation the most effectively, but I am attempting to copy products into newly created sheets if they are the same product.
For example if there are 4 products that are "Apples"
and two that are "Oranges"
. Then I would like to create a new sheet for each product, rename the new sheet after said product, and place each row containing said product into each new sheet.
Currently, my program is running through a double loop. The first loop runs through each row in the first sheet, and the second loops through the sheet names.
The problem I am running into is with the first loop: the code creates a new sheet for the first product in the list, which is fine. But the next product in the list is the same product, so it should be placed into the newly-created sheet. However, my code creates another new sheet, attempts to rename it after the product next in the list, and then errors and says
"You can't name the sheet after a sheet named the same thing".
Now that is a Catch-22, because my if statement should catch it, but it doesn't.
I am running this is an outside workbook, after the program runs, I will save it under a different file name, so I'd prefer not to paste the date into the macro file and just keep it as a separate file.
CODE:
Dim fd As FileDialog
Dim tempWB As Workbook
Dim i As Integer
Dim rwCnt As Long
Dim rngSrt As Range
Dim shRwCnt As Long
Set fd = Application.FileDialog(msoFileDialogFilePicker)
For i = 1 To fd.SelectedItems.Count
Set tempWB = Workbooks.Open(fd.SelectedItems(i))
With tempWB.Worksheets(1)
For y = 3 To rwCnt
For Z = 1 To tempWB.Sheets.Count
If .Cells(y, 2).Value = tempWB.Sheets(Z).Name Then
.Rows(y).Copy
shRwCnt = tempWB.Worksheets(Z).Cells(Rows.Count, 1).End(xlUp).Row
tempWB.Worksheets(Sheets.Count).Range("A" & shRwCnt).PasteSpecial Paste:=xlPasteAllUsingSourceTheme, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
ElseIf tempWB.Sheets(Z).Name <> .Range("B" & y).Value Then
If Z = tempWB.Sheets.Count Then
.Range("A1:AQ2").Copy
tempWB.Worksheets.Add after:=tempWB.Worksheets(Sheets.Count)
tempWB.Worksheets(Sheets.Count).Name = .Cells(y, 2).Value
tempWB.Worksheets(Sheets.Count).Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.Rows(y).Copy
tempWB.Worksheets(Sheets.Count).Range("A3").PasteSpecial Paste:=xlPasteAllUsingSourceTheme, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
End If
Next Z
Next y
End With
Next i