我有一个包含许多工作表的Excel工作簿。
我正在尝试将包含内容的最后一行复制到某些工作表中的下一个空行。
例如,我的工作表名为Hoja1,Hoja2,Hoja3,...,Hoja20,但我只需要在工作表Hoja1,Hoja3,Hoja4中这样做。Hoja12、Hoja13和Hoja20。
这是我的代码:
Sub sale()
Sheets(Array("Hoja1", "Hoja3", "Hoja4", "Hoja12", "Hoja13")).Select
Sheets("Hoja20").Activate
Range("A50000").End(xlUp).Select
Range(Selection, Selection.End(xlToRight)).Copy
Range("A50000").End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
End Sub
有时最后一行会被删除,而在Hoja3中,当复制最后一行时,会删除原始行中包含数据的最后一个单元格。
我尝试了这个方法:
Sub copylastrow()
Sheets(Array("Hoja1", "Hoja3", "Hoja4", "Hoja12", "Hoja13")).Select
Sheets("Hoja20").Activate
Range("A" & Rows.Count).End(xlUp).EntireRow.Copy
Range("A" & Rows.Count).End(xlUp).Offset(1).EntireRow.PasteSpecial
End Sub
它只复制Hoja20中的最后一行。
发布于 2020-01-13 22:59:49
我会把它分成两部分:一个是执行复制的函数,另一个是客户端子,它建立一个工作表的集合,并通过它们循环调用复制函数。
Option Explicit
Public Sub CopyLastRow(xlSheet As Worksheet)
xlSheet.Activate
xlSheet.Range("A" & Rows.Count).End(xlUp).EntireRow.Copy
xlSheet.Range("A" & Rows.Count).End(xlUp).Offset(1).EntireRow.PasteSpecial
End Sub
Sub DoWork()
Dim arrSheets As Object
Dim xlSheet As Worksheet
'// Turn off screen updating
Application.ScreenUpdating = False
'// Establish the collection of sheets
Set arrSheets = Sheets(Array("Hoja1", "Hoja3", "Hoja4", "Hoja12", "Hoja13"))
'// Loop through each sheet and copy the last row
For Each xlSheet In arrSheets
CopyLastRow xlSheet
Next xlSheet
'// Turn screen updating back on
Application.ScreenUpdating = True
End Sub
顺便说一句,如果您不关心复制最后一行的格式,那么简单地分配range值可能比使用Range对象的.Copy
和.PasteSpecial
方法更好。您可以这样做:
Public Sub CopyLastRowFaster(xlSheet as Worksheet)
xlSheet.Range("A" & Rows.Count).End(xlUp).Offset(1).EntireRow.Value = xlSheet.Range("A" & Rows.Count).End(xlUp).EntireRow.Value
End Sub
https://stackoverflow.com/questions/59717240
复制相似问题