2016-08-23 40 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 
相关问题