jeffreybrown
Well-known Member
- Joined
- Jul 28, 2004
- Messages
- 5,152
Hi All,
Here is my table which is just a test sample of the larger table, but in the end, it is column 1 I want to base the new ws on.
Before Macro
The code below works fine through the first instance of the match and adds a new ws based on the name, but when it gets to the second match the macro tries to add the ws all over again and I get a run time error 1004 which states you can not add a ws and name it the same as one that already exist. I only have one sheet in my wb titled "AY". How can I also have the two column headers transfer to the new ws?
After Macro
Here is my table which is just a test sample of the larger table, but in the end, it is column 1 I want to base the new ws on.
Before Macro
Excel Workbook | ||||
---|---|---|---|---|
A | B | |||
1 | Unit | Count | ||
2 | 5 | 3 | ||
3 | 2 | 10 | ||
4 | 31 LGR SQ | 10 | ||
5 | 8 | 4 | ||
6 | 31 LGR SQ | 7 | ||
7 | 2 | 6 | ||
AY |
The code below works fine through the first instance of the match and adds a new ws based on the name, but when it gets to the second match the macro tries to add the ws all over again and I get a run time error 1004 which states you can not add a ws and name it the same as one that already exist. I only have one sheet in my wb titled "AY". How can I also have the two column headers transfer to the new ws?
Code:
Public Sub CopyUnit()
Dim N As String
Dim i As Long
Dim ws As Worksheet
Set ws = Sheets("AY")
N = Worksheets("PAS Codes").Range("L14").Value
For i = Range("A65334").End(xlUp).Row To 1 Step -1
With ws
If Cells(i, 1).Value = N Then
.Rows(i).Copy
Sheets.Add.Name = N
Rows("1:1").Select
ActiveSheet.Paste
End If
End With
Next i
Application.CutCopyMode = False
End Sub
Excel Workbook | ||||
---|---|---|---|---|
A | B | |||
1 | Unit | Count | ||
2 | 31 LGR SQ | 7 | ||
3 | 31 LGR SQ | 10 | ||
31 LGR SQ |