循环文件夹和子文件夹 - 多个文件夹路径

时间:2017-07-31 07:54:07

标签: excel-vba directory subdirectory vba excel

基本上,我在excel工作表中有一个文件夹路径列表,如下图所示: List of Folder Path

我想遍历所有子文件夹(最多3,4层),找到名为" Report"的文件夹。 ,图中列出的每个文件夹路径都包含"报告"文件夹中。

Sub SearchReport()

    Dim FileSystem As Object

    counter = 2
    Do While Range("A" & counter).Value <> ""   'do when Range A is not empty (folder path)

        If Range("C" & counter).Value = "Yes" Then  'check Range C, do when Range C = Yes
            HostFolder = Range("A" & counter).Value & "\"
            Set FileSystem = CreateObject("Scripting.FileSystemObject")
            Report FileSystem.getFolder(HostFolder) 'HostFolder is the folder path from Range A
            counter = counter + 1
        Else
            counter = counter + 1
        End If
    Loop
End Sub

Sub Report(Folder)
    Dim SubFolder
    Dim subfld As Folder
    Dim subfldr As Folder
    Dim File As File
    Dim MyPath As String
    Dim Wksht As Worksheet
    Dim wbk As Workbook

           For Each SubFolder In Folder.SubFolders  'loop through subfolders in the  first folder path
            Do While SubFolder.Name = "Report"  'look for a folder named "Report"

                MyPath = SubFolder.Path & "\"
                Filename = Dir(MyPath & "*al.dat")  'look for files which is ended with "al.dat" in the "Report" folder

                  Do While Len(Filename) > 0    'open the files
                    Set Wksht = Worksheets.Add
                    Wksht.Name = Left(Filename, Len(Filename) - 10)

                    Set wbk = Workbooks.Open(MyPath & Filename)
                    Set Wrksht = wbk.Worksheets(1)

                    Wrksht.Cells.Copy Wksht.Cells
                    wbk.Close True
                    Filename = Dir
                  Loop
            Loop
              Report SubFolder
           Next
End Sub

我可以遍历子文件夹来搜索&#34;报告&#34;我修改了从网上获取的代码后的文件夹,还导入了该文件夹中的所有文件。问题是,它重复并重复循环在同一文件夹中,无法进入下一个文件夹路径,如上图所示。我试图调试几天但仍然失败,所以我决定寻求社区的帮助。

我知道有很多关于循环浏览文件夹和子文件夹的问题已得到解答,但它没有帮助,因为我的情况是我需要编码循环遍历所有列出的文件夹路径。
任何帮助或建议表示赞赏,谢谢!

0 个答案:

没有答案