如何将多个Excel文件合并成一个且保留原有数据?事实上,我们可以借用Excel宏命令来处理该操作,并且保留原有数据,建立多个Sheet页,具体操作请看下文多个Excel文件合并成一个的方法。
如何将多个Excel文件合并成一个且保留原有数据?
1、将需合并的Excel文件放在同一个文件夹中,并这个文件中新建一个Excel文件。
2、打开新建的Excel文件,按 Alt + F11 键,打开宏,选择视图→代码窗口。
3、将下面的代码拷贝进去:
01Sub sheets2one()02'定义对话框变量03Dim cc As FileDialog04Set cc = Application.FileDialog(msoFileDialogFilePicker)05Dim newwork As Workbook06Set newwork = Workbooks.Add07With cc08If .Show = -1 Then09Dim vrtSelectedItem As Variant10Dim i As Integer11i = 112For Each vrtSelectedItem In .SelectedItems13Dim tempwb As Workbook14Set tempwb = Workbooks.Open(vrtSelectedItem)15tempwb.Worksheets(1).Copy Before:=newwork.Worksheets(i)16newwork.Worksheets(i).Name = VBA.Replace(tempwb.Name, ".xls", "")17tempwb.Close SaveChanges:=False18i = i + 119Next vrtSelectedItem20End If21End With22Set cc = Nothing23End Sub复制代码Sub sheets2one()'定义对话框变量Dim cc As FileDialogSet cc = Application.FileDialog(msoFileDialogFilePicker)Dim newwork As WorkbookSet newwork = Workbooks.AddWith ccIf .Show = -1 ThenDim vrtSelectedItem As VariantDim i As Integeri = 1For Each vrtSelectedItem In .SelectedItemsDim tempwb As WorkbookSet tempwb = Workbooks.Open(vrtSelectedItem)tempwb.Worksheets(1).Copy Before:=newwork.Worksheets(i)newwork.Worksheets(i).Name = VBA.Replace(tempwb.Name, ".xls", "")tempwb.Close SaveChanges:=Falsei = i + 1Next vrtSelectedItemEnd IfEnd WithSet cc = NothingEnd Sub
4、点击运行选项运行宏命令。
5、之后弹出选择对话框,选择要批量合并的Excel名,确定即可。
6、程序运行完毕后,会自动生成一个工作簿,工作簿内包含所有需合并的Excel文件,将工作簿另存为即可。
以上步骤便是,合并后的Excel文档会献出多个Sheet页,我们可以很方便的切换了解。
转载请注明:范的资源库 » 如何将多个Excel文件合并成一个且保留原有数据?