我有一個包含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