VBA 循环遍历多个文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13002427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:09:38  来源:igfitidea点击:

VBA Loop through multiple folders

excelvbaloopsexcel-vba

提问by mburke05

Possible Duplicate:
get list of subdirs in vba

可能的重复:
获取 vba 中的子目录列表

I'm trying to apply the following code, which applies to running this VBA loop through all files in a folder, to make it run through all folders within one folder.

我正在尝试应用以下代码,该代码适用于在文件夹中的所有文件中运行此 VBA 循环,以使其在一个文件夹中的所有文件夹中运行。

Is there any way that this is possible?

有什么办法可以做到吗?

I have about 50 folders, each with the same named workbook, so I'd need to try and make it more efficient.

我有大约 50 个文件夹,每个文件夹都有相同命名的工作簿,所以我需要尝试使其更有效率。

Thanks!

谢谢!

Sub LoopFiles()

    Application.DisplayAlerts = False    
    Dim strDir As String, strFileName As String
    Dim wbCopyBook As Workbook
    Dim wbNewBook As Workbook

    strDir = "C:\Documents and Settings\mburke\Desktop\Occupancy 2013\"
    strFileName = Dir(strDir & "*.xlsm")

    Set wbNewBook = Workbooks.Add

    Do While strFileName <> ""
        Set wbCopyBook = Workbooks.Open(strDir & strFileName)
        wbCopyBook.Sheets(1).Copy Before:=wbNewBook.Sheets(1)
        wbCopyBook.Close False
        strFileName = Dir
    Loop

    Application.DisplayAlerts = True
End Sub

回答by Michael Rodrigues

Sure you can! Just add another LoopDirectories method that does a DIR for folders.

你当然可以!只需添加另一个 LoopDirectories 方法,该方法为文件夹执行 DIR。

Change the LoopFiles method a bir to accept a directory parameter:

将 LoopF​​iles 方法更改为 bir 以接受目录参数:

Sub LoopFiles(directory As String)

    Application.DisplayAlerts = False

    Dim strDir As String, strFileName As String
    Dim wbCopyBook As Workbook
    Dim wbNewBook As Workbook


    strFileName = Dir(directory & "*.xlsm")

    Set wbNewBook = Workbooks.Add

    Do While strFileName <> ""
        Set wbCopyBook = Workbooks.Open(directory & strFileName)
        wbCopyBook.Sheets(1).Copy Before:=wbNewBook.Sheets(1)
        wbCopyBook.Close False
        strFileName = Dir
    Loop

    Application.DisplayAlerts = True
End Sub

Then call the LoopFiles method for each folder in your LoopDirecotries method.

然后在 LoopDirecotries 方法中为每个文件夹调用 LoopF​​iles 方法。