工作中经常会用到的把几个Excel文件合并到一个,或者是把一个Excel文件里的所有Sheet合并到一个Sheet来进行统计。下面分别提供用vba宏来解决这两个问题的方法。
1、合并Excel文件
打开一个空Excel文件,Alt+F11,插入一个模块,开始写代码:
Sub MergeWorkbooks()Dim FileSetDim i As IntegerOn Error GoTo 0Application.ScreenUpdating = FalseFileSet = Application.GetOpenFilename(FileFilter:="Excel 2003(*.xls),*.xls,Excel 2007(*.xlsx),*.xlsx", _MultiSelect:=True, Title:="选择要合并的文件")If TypeName(FileSet) = "Boolean" ThenGoTo ExitSubEnd IfFor Each Filename In FileSetWorkbooks.Open FilenameSheets().Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)NextExitSub:Application.ScreenUpdating = TrueEnd Sub
这段代码的作用:它首先打开一个文件选择框,你可以选择一个或多个文件,然后把这些文件里的所有Sheet合并到当前这个工作簿里来,有重名的Sheet会自动在后面加数字。
2、合并一个EXCEL多个sheet的内容到一个汇总sheet
同上,再添加一个模块吧,代码如下:
Function LastRow(sh As Worksheet)On Error Resume NextLastRow = sh.Cells.Find(what:="*", _After:=sh.Range("A1"), _Lookat:=xlPart, _LookIn:=xlFormulas, _SearchOrder:=xlByRows, _SearchDirection:=xlPrevious, _MatchCase:=False).RowOn Error GoTo 0
End FunctionSub MergeSheets()Dim sh As WorksheetDim DestSh As WorksheetDim Last As LongDim shLast As LongDim CopyRng As RangeDim StartRow As LongApplication.ScreenUpdating = FalseApplication.EnableEvents = False'新建一个“汇总”工作表Application.DisplayAlerts = FalseOn Error Resume NextActiveWorkbook.Worksheets("汇总").DeleteOn Error GoTo 0Application.DisplayAlerts = TrueSet DestSh = ActiveWorkbook.Worksheets.AddDestSh.Name = "汇总"'开始复制的行号,忽略表头,无表头请设置成1StartRow = 2For Each sh In ActiveWorkbook.WorksheetsIf sh.Name <> DestSh.Name ThenLast = LastRow(DestSh)shLast = LastRow(sh)If shLast > 0 And shLast >= StartRow ThenSet CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast))If Last + CopyRng.Rows.Count > DestSh.Rows.Count ThenMsgBox "内容太多放不下啦!"GoTo ExitSubEnd IfCopyRng.CopyWith DestSh.Cells(Last + 1, "A").PasteSpecial xlPasteValues.PasteSpecial xlPasteFormatsApplication.CutCopyMode = FalseEnd WithEnd IfEnd IfNextExitSub:Application.GoTo DestSh.Cells(1)DestSh.Columns.AutoFitApplication.ScreenUpdating = TrueApplication.EnableEvents = TrueEnd Sub
这段代码的作用:它会新建一个叫做“汇总”的工作表,然后把当前工作簿里的所有Sheet里有数据的内容都复制到“汇总”表里。提示:如果数据表里的内容没有表头的话需要把StartRow = 2改成StartRow = 1。