Я пытаюсь перебрать все файлы Excel в подпапках папки, указанной пользователем, и скопировать и вставить данные в новую рабочую книгу с именем «Компиляция».Этот код работает до создания и сохранения новой рабочей книги, но данные не будут копироваться и вставляться в рабочую книгу.
Может кто-нибудь помочь, пожалуйста?
Sub LoopCopyPasteSubfolders()
Dim fso As Object
Dim wb As Object
Dim folder As Object
Dim subfolder As Object
Dim MyPath As String
Dim MyFile As String
Dim FdrPicker As FileDialog
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FdrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FdrPicker
.Title = "Select a Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
MyPath = .SelectedItems(1) & "\"
End With
NextCode:
'in case of cancel
If MyPath = "" Then GoTo ResetSettings Else
Dim NewWB As Workbook
Set NewWB = Workbooks.Add
ActiveWorkbook.SaveAs Filename:="C:\Batch\Compilation.xlsx", FileFormat:=xlWorkbookNormal
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.getfolder(MyPath)
Set subfolder = folder.subfolders
For Each subfolder In folder.subfolders
Set wb = subfolder.Files
For Each wb In subfolder.Files
If fso.GetExtensionName(wb.Path) = "*.xls*" Then
Workbooks.Open wb, ReadOnly:=True
Range("A1:M1").End(xlDown).Copy
For Each cell In Workbooks("Compilation").Worksheets("Sheet1").Columns(1).Cells
If IsEmpty(cell) = True Then cell.PasteSpecial Paste:=xlPasteValues
'exit when value pasted to the first empty row
Exit For
Next cell
End If
Next wb
Next subfolder
'reset settings to default
ResetSettings:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End Sub