将多个工作表中的所有数据复制到一个新工作表中

时间:2016-07-18 19:29:26

标签: excel excel-vba vba

这是我的情况:我想从多个excel表中复制表并将它组合成一个新表。到目前为止我已经选择了表,并创建了一个新表来组合数据,但是它确实如此。合并时不要选择表格的最后一行。谢谢你的帮助:

 Sub Trytocombine()

 Dim J As Integer


On Error Resume Next
Sheets(1).Select
Worksheets.Add ' add a sheet in first place
Sheets(1).Name = "For Drafting"

' copy headings
Sheets(2).Activate
Range("A1").EntireRow.Select
Selection.CurrentRegion.Select
Selection.Copy Destination:=Sheets(1).Range("A1")

' work through sheets
For J = 2 To Sheets.Count ' from sheet 2 to last sheet
    Sheets(J).Activate ' make the sheet active
    Range("A1").Select
    Selection.CurrentRegion.Select ' select all cells in this sheets

    ' select all lines except title
    Selection.Offset(0, 0).Resize(Selection.Rows.Count - 1).Select

    ' copy cells selected in the new sheet on last line
    Selection.Copy Destination:=Sheets(1).Range("A65536").End(xlUp)(2)
Next
End Sub

1 个答案:

答案 0 :(得分:1)

重构为avoid select(并在最后一行后复制):

Sub Combine()

Worksheets.Add ' add a sheet in first place
Sheets(1).Name = "For Drafting"

' copy headings
Sheets(1).Range("A1").EntireRow.Value = Sheets(2).Range("A1").EntireRow.Value 'not most effecient, but will do for this

' work through sheets
Dim J As Integer
For J = 2 To Sheets.Count ' from sheet 2 to last sheet
    With Sheets(J)
        .Range(.Cells(2,1),.Cells(.Range("A" & .Rows.Count).End(xlUp).Row,.Cells(2,.Columns.Count).End(xlToLeft).Column)).Copy _ 
             Sheets(1).Range("A" & Rows.Count).End(xlUp).Offset(2)
    End With
Next

End Sub