繁体   English   中英

如何复制一张纸中的特定列并粘贴到另一张纸中的不同范围?

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

我是一个初学者,下面有这段代码,但这只是复制工作表的最后一行并将其粘贴到工作表2范围内。 基本上,空行不会更新。 并且还会引发运行时错误1004-应用程序定义或对象定义的错误。 任何帮助将非常感激。

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

可以说这是工作表1工作表1

这是sheet2: sheet2:

标头的命名稍有不同,并且位置也有变化。 并且工作表1中的最后一行是可变的。

尝试此操作,始终最好避免复制和粘贴。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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