2016-08-23 133 views
0

我是新來的excel宏。我想創建一個讀取具有多個子文件夾的單個主文件夾的宏。 它正在每個子文件夾的第一個子文件夾中尋找.xls文件(它會一直持續到找到.xls爲止)。在其上將打開該文件,對文件執行編輯,保存並關閉,返回到前一個子文件夾向下移動到第二個子文件夾。重複,直到沒有更多的子文件夾在該文件夾內。它持續迭代子文件夾,直到它已經通過所有子文件夾和帶有主文件夾的文件。如何掃描整個主文件夾中的多個子文件夾?

在找到它需要編輯的.xls文件之前,它可能是4或5個子文件夾。

+3

歡迎S.O!你有嘗試過什麼嗎?如果是這樣,請提供代碼,看看[tour](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/help/how-to-ask )。友情提醒:StackOverflow不是「我們爲您代碼」的服務提供商。 [VBA簡介](https://blog.udemy.com/excel-macros-tutorial/)提示:嘗試在論壇中搜索。 – Sgdva

回答

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 
相關問題