你真幸運,我在工作:)一些空閒時間
您需要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
歡迎S.O!你有嘗試過什麼嗎?如果是這樣,請提供代碼,看看[tour](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/help/how-to-ask )。友情提醒:StackOverflow不是「我們爲您代碼」的服務提供商。 [VBA簡介](https://blog.udemy.com/excel-macros-tutorial/)提示:嘗試在論壇中搜索。 – Sgdva