【问题标题】:Execute macro on all files in a folder and subfolder对文件夹和子文件夹中的所有文件执行宏
【发布时间】:2021-01-08 14:46:28
【问题描述】:

我想为 文件夹和子文件夹中的所有 doc 和 docx 文件执行 Word 宏。我的代码只执行文件夹的宏(而不是子文件夹)。有没有办法做到这一点?

到目前为止我的宏:

Sub Aufruf()
Dim File
Dim path As String

' Path to your folder. MY folder is listed below. I bet yours is different.
' make SURE you include the terminating "\"
path = "C:\Users\RHU\Desktop\VBA\"

File = Dir(path & "*.doc*")
Do While File <> ""
Documents.Open fileName:=path & File

' This is the call to the macro you want to run on each file the folder
Call Datumsfelder


' Saves the file
ActiveDocument.Save
ActiveDocument.Close
' set file to next in Dir
File = Dir()
Loop
End Sub

【问题讨论】:

    标签: vba ms-word ms-office


    【解决方案1】:

    转到工具 -> 参考并从那里添加 Microsoft 脚本运行时。这将使您能够访问文件系统对象 (FSO)。它包含许多有用的功能,例如获取子文件夹。

    然后你可以用下面的代码循环它们:

    Sub myFunction()
    
    Dim FSO As New FileSystemObject
    Dim myFolder As Folder
    Dim anotherFolder As Folder
    Dim myFile as File
    
    Set myFolder = FSO.GetFolder("C:\a\")
    
    For Each anotherFolder In myFolder.SubFolders
        Debug.Print anotherFolder
        For Each myFile In anotherFolder.Files
            'Here the myFile object will allow you to open each file in the current folder
             Documents.open myFile.Path
             'Do more stuff, then save and close the file
        Next
    Next
    
    End Sub
    

    请注意,这只会深入一层。如果需要更深入,则需要加入多个 For 循环。

    【讨论】:

    • 这对我不起作用。你能给我写一个代码可以执行的例子吗?非常感谢!
    • 错误信息是什么?它在哪里失败?报告代码中的问题时,请提供尽可能多的信息。
    • 我没有错误信息什么的。宏在打开的文件而不是文件夹中的文件上执行。你知道这是什么吗?
    • 我已经用更多解释编辑了我的答案。您需要根据您的需要调整该代码。
    • 谢谢!但这行不通。仅适用于一个子文件夹...
    猜你喜欢
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2017-04-04
    相关资源
    最近更新 更多