Reputation: 999
set ws1 As SheetA
set ws2 As Target
With ws1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Lastrow = ws1.Range("B" & Rows.Count).End(xlUp).Row
For i = 1 To Lastcol
For l = 4 To lastrow
ws1.Cells(l, i).Copy ws2.Range("a65536").End(xlUp).Offset(1, 0)
Next l
Next i
I am trying to copy all the columns in one sheet to another sheet one below the another. Basically copying Column A of Sheet1 to Column A of Sheet2 and then Column B of Sheet1 below Column A of Sheet2 .
Data starts from row 4th of Sheet A in every column, so I kept the second For Loop
running from 4. Any help is greatly appreciated as I am stuck for hours now. When I run the code it goes in to infinite loop.
Upvotes: 0
Views: 177
Reputation: 19727
If the Lastrow
for every column is the same (referenced to B
Column) then you can try below:
With ws1
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
End With
Dim i As Long, LastRow2 As Long
For i = 0 To LastCol - 1
With ws2
LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
ws1.Range("A4:A" & LastRow).Offset(0, i).Copy .Range("A" & LastRow2)
End With
Next
You don't need to copy each cell one by one by doing nested For Loop
.
You can set the first group of cell to copy (Range("A4:A" & LastRow)
), then just use Offset
to copy the next column using just one(1) loop.
If LastRow
for every column is different, you can try:
Dim LastCol As Long, LastRow As Long
LastCol = ws1.Cells(1, ws1.Columns.Count).End(xlToLeft).Column
Dim i As Long, LastRow2 As Long
For i = 0 To LastCol - 1
LastRow = ws1.Cells(ws1.Rows.Count, i + 1).End(xlUp).Row
With ws2
LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
ws1.Range("A4:A" & LastRow).Offset(0, i).Copy .Range("A" & LastRow2)
End With
Next
Upvotes: 1