【问题标题】:Copy all data from multiple sheets into one new sheet将多张工作表中的所有数据复制到一张新工作表中
【发布时间】:2016-07-18 19:29:26
【问题描述】:

这是我的情况:我想从多个 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

【问题讨论】:

  • 我通常不使用“Offset”和“Selection”之类的东西,但我猜“Selection.Offset(0, 0)”应该是“Selection.Offset(1, 0)"。就目前而言,我认为它将第一行复制到最后一行 - 1。(但 Scott 的方法是一种更受欢迎的做事方式。)
  • 只需将.Offset(0, 0) 替换为.Offset(1, 0)

标签: excel vba


【解决方案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

【讨论】:

  • 我在您的复制标题任务中收到错误:对象不支持此方法或属性
  • @mattrashty - 立即尝试。忘记范围说明。
  • 抱歉,Scott,除了这一行之外,我得到了同样的错误:Sheets(J).CurrentRegion.Resize(Sheets(J).CurrentRegion.Rows.Count - 1).Copy _ Sheets(1) .Range("A" & Rows.Count).End(xlUp).Offset(1)
  • 我的原始代码运行良好,除了最后一行进入
  • 终于成功了!我衷心感谢您的帮助。谢谢斯科特
猜你喜欢
  • 2016-03-23
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多