简体   繁体   中英

How to copy specific columns from one sheet and paste in another sheet in a different range?

I am a beginner and I have this code below, but this just copies the last row from sheet and pastes into sheet 2 range. Basically the empty row is not getting updated. And also throws run time error 1004 - Application defined or object defined error. Any help would be much appreciated.

Sub copypaste()
Dim lastrow As Long, erow As Long

lastrow = ThisWorkbook.Worksheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow

Sheet1.Cells(i, 3).Copy
erow = ThisWorkbook.Worksheets("sheet2").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 2)
Sheet1.Cells(i, 14).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 4)
Sheet1.Cells(i, 6).Copy
Sheet1.Paste Destination:=Worksheets("Sheet2").Cells(erow, 3)

Next i

Application.CutCopyMode = False
ThisWorkbook.Worksheets("sheet2").Columns().AutoFit
Range("A1").Select

End Sub

Lets say this is sheet 1 sheet 1

and this is sheet2: sheet2:

Where the headers are slightly different in naming and there's also a position change. And the last row in sheet 1 is varied.

Try this, always better to avoid copy and paste.

Sub copypaste()
Dim lastrow As Integer, erow As Integer, sheet1 As Worksheet, sheet2 As Worksheet

Set sheet1 = Worksheets("Sheet1")
Set sheet2 = Worksheets("Sheet2")
lastrow = sheet1.Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
    erow = sheet2.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
    sheet2.Cells(erow, 2) = sheet1.Cells(i, 3)
    sheet2.Cells(erow, 3) = sheet1.Cells(i, 6)
    sheet2.Cells(erow, 4) = sheet1.Cells(i, 14)
Next i

'ThisWorkbook.Worksheets("Sheet2").Columns().AutoFit
'sheet1.Cells(1, 1).Activate
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM