我有一个包含n个工作表的Excel工作簿。我想将每张纸上的数据合并到一张纸上。来自第一张纸的页眉和数据应该在上面,第二张纸上的数据应该在下面,依此类推。所有工作表都具有相同的列和标题结构。所以,标题应该只出现一次,即从第一张表格获取标题和数据,并从剩余表格中获取数据。我有以下代码:合并多个工作表时的数据重叠
Sub Combine()
'This macro will copy all rows from the first sheet
'(including headers)
'and on the next sheets will copy only the data
'(starting on row 2)
Dim i As Integer
Dim j As Long
Dim SheetCnt As Integer
Dim lstRow1 As Long
Dim lstRow2 As Long
Dim lstCol As Integer
Dim ws1 As Worksheet
With Application
.DisplayAlerts = False
.EnableEvents = False
.ScreenUpdating = False
End With
On Error Resume Next
'Delete the Target Sheet on the document (in case it exists)
Sheets("Target").Delete
'Count the number of sheets on the Workbook
SheetCnt = Worksheets.Count
'Add the Target Sheet
Sheets.Add after:=Worksheets(SheetCnt)
ActiveSheet.Name = "Target"
Set ws1 = Sheets("Target")
lstRow2 = 1
'Define the row where to start copying
'(first sheet will be row 1 to include headers)
j = 1
'Combine the sheets
For i = 1 To SheetCnt
Worksheets(i).Select
'check what is the last column with data
lstCol = ActiveSheet.Cells(1, ActiveSheet.Columns.Count).End(xlToLeft).Column
'check what is the last row with data
lstRow1 = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
'Define the range to copy
Range("A2:G2" & j, Cells(lstRow1, lstCol)).Select
'Copy the data
Selection.Copy
ws1.Range("A2:G2" & lstRow2).PasteSpecial
Application.CutCopyMode = False
Selection.Offset(1, 0).Resize(Selection.Rows.Count - 1).Select
'Define the new last row on the Target sheet
lstRow2 = ws1.Cells(65535, "A").End(xlUp).Row + 1
'Define the row where to start copying
'(2nd sheet onwards will be row 2 to only get data)
j = 3
Next
With Application
.DisplayAlerts = True
.EnableEvents = True
.ScreenUpdating = True
End With
Sheets("Target").Select
Cells.EntireColumn.AutoFit
Range("A1").Select
End Sub
有了这段代码,我所有工作表中的数据都被重叠了。我希望数据是一个在另一个之下。
:它工作的部分正确。对于原始数据,一些垃圾数据也正在被复制(称为Errorcodeupdated)。我该如何避免这种情况? – Madhu
我的代码会查找曾经使用的最后一行数据。您的工作表可能在数据下有空单元格,其中包含被遗忘的公式或单元格格式。如果您在工作表上按Ctrl + End,它将显示Excel认为上次使用的单元格的内容。如果看到多余的行和列,通过选择整行来删除它们,右键单击左边距并选择删除。如果您只是选择空白区域并按Del键,则不能解决问题。删除所有额外的列。如果你有太多的手册来做这个手动让我知道,我们将以另一种方式解决 –
请帮我删除垃圾数据,我无法解决问题,因为我有超过10张 – Madhu