Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 对文件夹和子文件夹中的所有文件执行宏_Vba_Ms Word_Ms Office - Fatal编程技术网

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

Vba 对文件夹和子文件夹中的所有文件执行宏,vba,ms-word,ms-office,Vba,Ms Word,Ms Office,我想对文件夹及其子文件夹中的所有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 "\"

我想对文件夹及其子文件夹中的所有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
Sub-Aufruf()
暗文件
将路径设置为字符串
'文件夹的路径。我的文件夹列在下面。我打赌你的不一样。
'确保包含终止“\”
path=“C:\Users\RHU\Desktop\VBA\”
File=Dir(路径&“*.doc*”)
文件“”时执行此操作
文档。打开文件名:=路径和文件
'这是对要在文件夹中的每个文件上运行的宏的调用
呼叫Datumsfeld
'保存文件
ActiveDocument.Save
ActiveDocument。关闭
'将文件设置为目录中的下一个
File=Dir()
环
端接头

转到工具->参考,然后从中添加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循环。

这对我不适用。你能给我写一个例子,里面有可以执行的代码吗?非常感谢你!错误信息是什么?它在哪里失败?请在代码中报告问题时提供尽可能多的信息。我没有错误消息或其他信息。宏在打开的文件上执行,而不是在文件夹中的文件上执行。你知道这是什么吗?我编辑了我的答案,并做了更多解释。您需要根据自己的需要修改代码。谢谢!但这是行不通的。仅适用于一个子文件夹。。。