将一个excel文档中的多个工作表进行合并为一个工作表
打开要合并的工作簿
按alt+F11进入VBA工程界面
新建一个模块
复制下面的代码,然后执行即可
作用结果是:
它会新建一个叫做“汇总”的工作表,然后把当前工作簿里的所有Sheet里有数据的内容都复制到“汇总”表里。提示:如果数据表里的内容没有表头的话需要把StartRow = 2改成StartRow = 1
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(what:="*", _
After:=sh.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Sub MergeSheets()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim shLast As Long
Dim CopyRng As Range
Dim StartRow As Long
Application.ScreenUpdating = False
Application.EnableEvents = False
"新建一个“汇总”工作表
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("汇总").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "汇总"
StartRow = 2
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> DestSh.Name Then
Last = LastRow(DestSh)
shLast = LastRow(sh)
If shLast > 0 And shLast >= StartRow Then
Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "内容太多放不下啦!"
GoTo ExitSub
End If
CopyRng.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End If
End If
Next
ExitSub:
Application.GoTo DestSh.Cells(1)
DestSh.Columns.AutoFit
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub