复制动态范围并从一个工作表追加到另一个工作表

时间:2015-03-25 13:58:42

标签: vba excel-vba excel-2010 excel

我有3个数据表都具有相同的标题(列)。我需要将所有数据复制到一张纸上。每次运行报告时,每个数据表的行数都会有所不同。列数始终是常量。如何从表2和表3复制数据并附加到表1?

1 个答案:

答案 0 :(得分:0)

假设您有三张名为Sheet 1:3的表格,其中包含A到C中的数据。

Sub combine_Sheets()

'Declare variables
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim sht3 As Worksheet
Dim lastRow As Long

'Set variables
Set sht1 = Sheets("Sheet1")
Set sht2 = Sheets("Sheet2")
Set sht3 = Sheets("Sheet3")

'Copy Sheet 2 to Sheet 1

'Find Last row on Sheet 1
lastRow = Cells(sht1.Rows.Count, "A").End(xlUp).Row

'Copy Sheet 2 data to bottom of Sheet 1
sht2.Range("A2:C" & Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row).Copy _
    Destination:=sht1.Range("A" & lastRow + 1)

'Copy Sheet 3 to Sheet 1

'Find new Last row on Sheet 1
lastRow = Cells(sht1.Rows.Count, "A").End(xlUp).Row

'Copy Sheet 3 data to bottom of Sheet 1
sht3.Range("A2:C" & Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row).Copy _
    Destination:=sht1.Range("A" & lastRow + 1)

sht1.Activate

End Sub