I've got a working Excel VBA macro that splits one worksheet into multiple based on the values in a particular column. However, I can't figure out how to modify two things about this macro.
I'd like to add a text string to the name of each sheet. (Instead of naming the sheet with just the numeric value it's splitting on, I'd like it to read "<text> value"
I need to copy column widths onto the new sheets. This macro currently copies formatting correctly, but I'm losing column widths.
Sub Copy_Data()
Dim r As Range, LastRow As Long, ws As Worksheet
Dim LastRow1 As Long, MyColumn As String
Dim src As Worksheet
MyColumn = "C"
Set src = Sheets("Sheet1")
LastRow = src.Cells(Cells.Rows.Count, MyColumn).End(xlUp).Row
For Each r In src.Range(MyColumn & "4:" & MyColumn & LastRow)
On Error Resume Next
Set ws = Sheets(CStr(r.Value))
On Error GoTo 0
If ws Is Nothing Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = CStr(r.Value)
'This row adds a header from the source sheet
'1:3 selects the rows to copy
src.Rows("1:3").Copy ActiveSheet.Range("A1")
LastRow1 = Sheets(CStr(r.Value)).Cells(Cells.Rows.Count, MyColumn).End(xlUp).Row
src.Rows(r.Row).Copy Sheets(CStr(r.Value)).Cells(LastRow1 + 1, 1)
Set ws = Nothing
Else
LastRow1 = Sheets(CStr(r.Value)).Cells(Cells.Rows.Count, MyColumn).End(xlUp).Row
src.Rows(r.Row).Copy Sheets(CStr(r.Value)).Cells(LastRow1 + 1, 1)
Set ws = Nothing
End If
Next r
End Sub