我是excel宏的新手。我想创建一个宏来读取一个包含多个子文件夹的master文件夹。 它正在寻找.xls文件在每个子文件夹的第一个子文件夹中(它会一直运行直到找到.xls文件)。它将打开文件,对文件执行编辑,保存并关闭,返回上一个子文件夹向下移动到第二个子文件夹。重复直到该文件夹中不再有子文件夹。它不断迭代子文件夹,直到它通过masterfolder浏览了所有子文件夹和文件。
在找到需要编辑的.xls文件之前,它可能是4个或5个子文件夹。
答案 0 :(得分:1)
幸运的是,我有空闲时间在工作:)
根据您的需要,您需要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