问题
I'm trying to merge worksheets together into one workbook. I have a work book that has over 20 sheets. I was looking to create a macro that would merge sheets together (depending on their name) into a separate workbook.
So far this is the code that I have got: it mergers all the sheets in the workbook together but I would like to merge them by name.
Sub mergedata()
Sheets(1).Activate
lastrow = ActiveSheet.UsedRange.Rows.Count
For Each Sheet In Sheets
If Sheet.Index <> 1 Then
RowCount = Sheet.UsedRange.Rows.Count
Sheet.UsedRange.Copy Destination:=Sheets(1).Cells(lastrow + 1, 1)
lastrow = lastrow + RowCount
Sheet.UsedRange.Clear
End If
Next Sheet
End Sub
回答1:
You need to add one additional if statements in your loop. This could be like this:
'.....
For Each Sheet In Sheets
If Sheet.Index <> 1 Then
If Sheet.Name = "NameOfSheet" or Sheet.Name = "NameIsCaseSensitive" then
RowCount = Sheet.UsedRange.Rows.Count
Sheet.UsedRange.Copy Destination:=Sheets(1).Cells(lastrow + 1, 1)
lastrow = lastrow + RowCount
Sheet.UsedRange.Clear
end if
End If
Next Sheet
'....
回答2:
I case you need the same but horizontaly (like I did) (w/o Names upgrade)
Sub mergedata_horizontal()
Sheets(1).Activate
lastcol = ActiveSheet.UsedRange.Columns.Count
For Each Sheet In Sheets
If Sheet.Index <> 1 Then
ColCount = Sheet.UsedRange.Columns.Count
Sheet.UsedRange.Copy Destination:=Sheets(1).Cells(1, lastcol + 1)
lastcol = lastcol + ColCount
Sheet.UsedRange.Clear
End If
Next Sheet
End Sub
来源:https://stackoverflow.com/questions/19182360/merge-more-than-3-excel-worksheets-into-one-workbook-with-macro