问题描述:若干个工作簿,每个工作簿里有一个工作表,如何利用VBA把若干工作簿里的表保存到一个新建的工作簿里,并单独成表?
4条回答 默认 最新
- VBA-守候 2021-11-30 04:42关注
VBA:用 Dir() 函数完成多工作簿合并
一 合并之前的文件夹和文件
文件夹
文件二 代码
Sub 多工作簿合并_Dir函数方法() Dim fName As String, fPath As String, suffStr As String, newFile As Workbook, opFile As Workbook, newSht As Worksheet Application.ScreenUpdating = False Set newFile = Workbooks.Add fPath = "E:\Zhuomian_CJ\ZZZ\VBA\答网友问" fName = Dir(fPath & "\", vbNormal) Do While fName <> "" suffStr = Split(fName, ".")(UBound(Split(fName, "."))) If suffStr Like "xls*" Then Set opFile = Workbooks.Open(fPath & "/" & fName) 'Debug.Print fName, suffStr Set newSht = newFile.Worksheets.Add(after:=newFile.Sheets(newFile.Sheets.Count)) opFile.Sheets(1).UsedRange.Copy newSht.Range("a1") newFile.ActiveSheet.Name = Left(fName, Len(fName) - Len(suffStr) - 1) & "_" & opFile.Sheets(1).Name Set newSht = Nothing opFile.Close xlDoNotSaveChanges Set opFile = Nothing End If fName = Dir Loop With newFile .SaveAs fPath & "/合并文件.xlsx" .Close xlSaveChanges End With Application.ScreenUpdating = True MsgBox "合并完成!" Set newFile = Nothing End Sub
三 执行代码后的文件效果
有任何【Office办公软件/办公自动化/文件批处理】的问题,欢迎和我交流!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用