【问题标题】:How do i scan multiple subfolders within an overall masterfolder? [duplicate]如何扫描整个主文件夹中的多个子文件夹? [复制]
【发布时间】:2016-12-30 06:37:50
【问题描述】:

我是 excel 宏的新手。我想创建一个读取单个主文件夹和多个子文件夹的宏。 它正在每个子文件夹的第一个子文件夹中查找 .xls 文件(它将继续运行,直到找到 .xls)。之后它将打开文件,对文件执行编辑,保存并关闭,返回上一个子文件夹,向下移动到第二个子文件夹。重复直到该文件夹​​中不再有子文件夹。它不断迭代子文件夹,直到它遍历所有子文件夹和主文件夹的文件。

在找到需要编辑的 .xls 文件之前,它可能有 4 或 5 个子文件夹。

【问题讨论】:

  • 欢迎来到 S.O!你试过什么吗?如果是这样,请提供代码,查看tourhow to ask。友情提示:StackOverflow 不是“我们为您编码”的服务提供商。 Introduction to VBA提示:也可以在论坛里搜索一下。

标签: vba excel


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2015-05-23
    • 1970-01-01
    • 2017-10-20
    • 2018-08-06
    相关资源
    最近更新 更多