|
貌似这个更好点儿,不会有空白sheet,会在程序文件同目录里生成一个新工作簿,看看这个如何?
Dim a, wb As Workbook
Sub tt()
Dim folderpath As String
' 使用FileDialog选择文件夹
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "请选择一个文件夹"
.AllowMultiSelect = False
If .Show = -1 Then
folderpath = .SelectedItems(1)
Else
MsgBox "未选择文件夹", vbExclamation
Exit Sub
End If
End With
Application.ScreenUpdating = False: Application.DisplayAlerts = False
FindAllFiles folderpath
wb.SaveAs ThisWorkbook.Path & "\" & "汇总工作簿.xlsx": wb.Close
Application.DisplayAlerts = True: Application.ScreenUpdating = True
Set fso = Nothing: Set wb = Nothing
End Sub
Sub FindAllFiles(fsPath As String) '采用递归穿透子文件夹
Dim fso As Object, file, folder, ws As Workbook
Set fso = CreateObject("scripting.filesystemobject").getfolder(fsPath)
For Each file In fso.Files
If file.Name Like "汇总*.xls*" Then '根据自己需要去更改
Set ws = Workbooks.Open(file.Path)
If a = 0 Then
ws.Sheets("汇总").Copy: Set wb = ActiveWorkbook
Else
ws.Sheets("汇总").Copy before:=wb.Sheets(1)
End If
ws.Close
wb.Sheets(1).Name = Split(file.Name, ".")(0)
a = a + 1
End If
Next
For Each folder In fso.subfolders '这就是递归
FindAllFiles fsPath & "\" & folder.Name
Next
End Sub
|
|