如何将所有归档行从一个表复制到另一个表

时间:2017-01-10 18:07:35

标签: excel excel-vba vba

我正在使用此代码将固定范围从工作表“t1”复制到工作表“t2”中的第一个空行。我想选择第一列上有值的所有行。例。在示例中,我想复制从john开始到44结尾的所有值(第2,3,4和5行)

1 Name address zip
2 john   aaa    11
3 jane   bbb    22
4 carl   ccc    33
5 jeff          44

这是我正在使用的代码。

Sub Botão1_Clique()

Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

Set copySheet = Worksheets("t1")
Set pasteSheet = Worksheets("t2")
copySheet.Range("A3:E3").Copy


pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True



End Sub

1 个答案:

答案 0 :(得分:2)

使用AutoFilter方法尝试下面的代码,以便在存在包含数据的行时允许复制工作表中的所有行(“t1”),但在A列中为空。

Option Explicit

Sub Botão1_Clique()

Application.ScreenUpdating = False

Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim Rng As Range

Set copySheet = Worksheets("t1")
Set pasteSheet = Worksheets("t2")

copySheet.UsedRange.AutoFilter
copySheet.UsedRange.AutoFilter Field:=1, Criteria1:="<>" ' <-- sut autofilter to exclude blanks on column A

Set Rng = Intersect(copySheet.UsedRange.Offset(1), copySheet.UsedRange.SpecialCells(xlCellTypeVisible)) ' <-- set range to only visible rows without the header row

Rng.Copy
pasteSheet.Range("A" & pasteSheet.Cells(pasteSheet.Rows.Count, "A").End(xlUp).Row + 1).PasteSpecial xlPasteValues   ' <-- paste values to first empty row at "t2" worksheet

Application.CutCopyMode = False
Application.ScreenUpdating = True

End Sub