如何扫描整个主文件夹中的多个子文件夹?

我是新来的macros。 我想要创build一个读取单个主文件夹和多个子文件夹的macros。 它正在寻找每个子文件夹的第一个子文件夹中的.xls文件(它会继续下去,直到find.xls)。 在其上将打开该文件,对文件执行编辑,保存并closures,返回到前一个子文件夹向下移动到第二个子文件夹。 重复,直到该文件夹​​中没有更多的子文件夹。 它不断遍历子文件夹,直到它已经通过所有的子文件夹和文件与主文件夹。

在find它需要编辑的.xls文件之前,它可能是4或5个子文件夹。

幸运的是我有一些工作上的空闲时间:)

您将需要recursion满足您的需求。 粗略的伪代码解释:

processFiles(folder) for each subfolder in folder for each file in subfolder Do modifications next call processFiles(subFolder) next end 

在VBA中,它看起来像这样:

 Sub openAllXlsFilesInSubDirectoriesAndModifyThem() Dim myPath As String myPath = ThisWorkbook.Path openAllXlsFilesInSubDirectoriesAndModifyThemRecursive (myPath) End Sub Private Sub openAllXlsFilesInSubDirectoriesAndModifyThemRecursive(currentFolder As String) ' Get a list of subdirs Dim fileSystem As Object Set fileSystem = CreateObject("Scripting.FileSystemObject") Dim folder Set folder = fileSystem.GetFolder(currentFolder) Dim file Dim Workbook ' Go down the folder tree Dim subFolder For Each subFolder In folder.SubFolders ' Go through all files in that subfolder For Each file In subFolder.Files ' Check if the file has the right extension Debug.Print file.Name If Right(file.Name, Len(file.Name) - InStrRev(file.Name, ".")) = "xls" Then ' Open the file Set Workbook = Workbooks.Open(file.Path & "\" & file.Name) ' Operate on the file Workbook.Sheets(1).Range("A1").Value = "edited" ' Save the file Workbook.Save ' Close the file Workbook.Close End If Next ' Check all subfolders of this subfolder openAllXlsFilesInSubDirectoriesAndModifyThemRecursive subFolder.Path Next End Sub