1、Excel多个文件合并为一个文件(在同一工作表里)新建一个excel文件,命名后保存到和与合并的100个文件同一个文件文件夹,摁 alt + f11,双击工程资源管理器里面的sheet1(sheet1),在右侧的代码区粘贴如下代码。运行。等候一会就OK了。 Sub 合并当前目录下所有工作簿的全部工作表() Dim MyPath, MyName, AWbName Dim Wb As Workbook, WbN As String Dim G As Long Dim Num As Long Dim BOX As String Application.ScreenUpdating = False M
2、yPath = ActiveWorkbook.Path MyName = Dir(MyPath & & *.xls) AWbName = ActiveWorkbook.Name Num = 0 Do While MyName If MyName AWbName Then Set Wb = Workbooks.Open(MyPath & & MyName) Num = Num + 1 With Workbooks(1).ActiveSheet .Cells(.Range(A65536).End(xlUp).Row + 2, 1) = Left(MyName, Len(MyName) - 4) F
3、or G = 1 To Sheets.Count Wb.Sheets(G).UsedRange.Copy .Cells(.Range(A65536).End(xlUp).Row + 1, 1) Next WbN = WbN & Chr(13) & Wb.Name Wb.Close False End With End If MyName = Dir Loop Range(A1).Select Application.ScreenUpdating = True MsgBox 共合并了 & Num & 个工作薄下的全部工作表。如下: & Chr(13) & WbN, vbInformation,
4、提示 End Sub 如果各文件都只有一个工作表,合并后要使各文件内容在不同工作表里(工作表名称与原文件相同),也就是说如10个文件,合并为一个文件,里面有10个工作表。则按上面的方法粘贴如下代码,然后单击“运行”“运行子过程(用户窗体),然后选择要合并的文件即生成新的文件。功能:把多个工作簿的第一个工作表合并到一个工作簿的多个工作表,新工作表的名称等于原工作簿的名称Sub Books2Sheets()定义对话框变量Dim fd As FileDialogSet fd = Application.FileDialog(msoFileDialogFilePicker)新建一个工作簿Dim new
5、wb As WorkbookSet newwb = Workbooks.AddWith fdIf .Show = -1 Then定义单个文件变量Dim vrtSelectedItem As Variant定义循环变量Dim i As Integeri = 1开始文件检索For Each vrtSelectedItem In .SelectedItems打开被合并工作簿Dim tempwb As WorkbookSet tempwb = Workbooks.Open(vrtSelectedItem)复制工作表tempwb.Worksheets(1).Copy Before:=newwb.Worksheets(i)把新工作簿的工作表名字改成被复制工作簿文件名,这儿应用于xls文件,即Excel97-2003的文件,如果是Excel2007,需要改成xlsxnewwb.Worksheets(i).Name = VBA.Replace(tempwb.Name, .xls, )关闭被合并工作簿tempwb.Close SaveChanges:=Falsei = i + 1Next vrtSelectedItemEnd IfEnd WithSet fd = NothingEnd Sub