对文件夹和子文件夹中的所有文件执行宏



我想为文件夹及其子文件夹中的所有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:UsersRHUDesktopVBA"
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

转到工具->引用,并从中添加Microsoft Scripting Runtime。这将允许您访问文件系统对象(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循环。

相关内容

  • 没有找到相关文章

最新更新