Forum Discussion
JDAV44
Apr 28, 2023Copper Contributor
VBA-copy row data to corresponding sheet
I was given the following table (much, much bigger but it gives the idea): I have corresponding sheets to column A with the main table = ALLDATA I found the following VBA code and used...
HansVogelaar
May 05, 2023MVP
Try this (it is not the fastest, but it should work).
Sub SplitData()
Const IDCol = "A"
Const HeaderRow = 1
Const FirstRow = 2
Dim SrcBook As Workbook
Dim SrcSheet As Worksheet
Dim TrgSheet As Worksheet
Dim SrcRow As Long
Dim LastRow As Long
Dim TrgRow As Long
Dim ID As String
Application.ScreenUpdating = False
Set SrcSheet = Worksheets("ALLDATA")
LastRow = SrcSheet.Cells(SrcSheet.Rows.Count, IDCol).End(xlUp).Row
For SrcRow = FirstRow To LastRow
ID = SrcSheet.Cells(SrcRow, IDCol).Value
Set TrgSheet = Nothing
On Error Resume Next
Set TrgSheet = Worksheets(ID)
On Error GoTo 0
If TrgSheet Is Nothing Then
Set TrgSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
TrgSheet.Name = ID
SrcSheet.Rows(HeaderRow).Copy Destination:=TrgSheet.Rows(HeaderRow)
End If
TrgRow = TrgSheet.Cells(TrgSheet.Rows.Count, IDCol).End(xlUp).Row + 1
SrcSheet.Rows(SrcRow).Copy Destination:=TrgSheet.Rows(TrgRow)
Next SrcRow
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub