VBA宏可在文件夹和子文件夹中打开/保存/关闭工作簿

时间:2019-03-22 11:55:12

标签: excel vba excel-2010

我有以下代码将打开/保存/关闭文件夹中的任何/所有工作簿。它很好用,但是,我还需要它包含子文件夹。如果可能,该代码无需对文件夹,子文件夹和文件的数量进行限制即可工作。

我正在使用Excel 2010,并且是VBA的新手-非常感谢您的帮助!

Sub File_Loop_Example()
    'Excel VBA code to loop through files in a folder with Excel VBA

    Dim MyFolder As String, MyFile As String

    'Opens a file dialog box for user to select a folder

    With Application.FileDialog(msoFileDialogFolderPicker)
       .AllowMultiSelect = False
       .Show
       MyFolder = .SelectedItems(1)
       Err.Clear
    End With

    'stops screen updating, calculations, events, and statsu bar updates to help code run faster
    'you'll be opening and closing many files so this will prevent your screen from displaying that

    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    'This section will loop through and open each file in the folder you selected
    'and then close that file before opening the next file

    MyFile = Dir(MyFolder & "\", vbReadOnly)

    Do While MyFile <> ""
        DoEvents
        On Error GoTo 0
        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
        ActiveWorkbook.Save
        Workbooks(MyFile).Close SaveChanges:=True
        MyFile = Dir
    Loop

    'turns settings back on that you turned off before looping folders

    Application.ScreenUpdating = True
    Application.DisplayStatusBar = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationManual

    MsgBox "Done!"

    End Sub

1 个答案:

答案 0 :(得分:0)

对于感兴趣的任何人,我找到了一个我可以适应并完全满足我想要的选择:

Sub Loop_Example()

Dim MyFolder As String
Dim file As Variant, wb As Excel.Workbook

With Application.FileDialog(msoFileDialogFolderPicker)
       .AllowMultiSelect = False
       .Show
       MyFolder = .SelectedItems(1)
       Err.Clear
    End With

Application.ScreenUpdating = False

For Each file In Filter(Split(CreateObject("WScript.Shell").Exec("CMD /C DIR """ & startFolder & "*.xl*"" /S /B /A:-D").StdOut.ReadAll, vbCrLf), ".")
    Set wb = Workbooks.Open(file)
    ActiveWorkbook.Save
    wb.Close SaveChanges:=True
    Set wb = Nothing
Next

Application.ScreenUpdating = True

    MsgBox "Done!"

End Sub