如何修改Word VBA宏遍历文件夹及子文件夹批量执行doc/docx处理宏
问题说明
现有编写的Word VBA宏仅能扫描目标根文件夹下的doc、docx格式文档,无法自动遍历嵌套的所有子文件夹,导致存放在子目录中的文件无法被执行自定义宏Datumsfelder。
原有宏代码逻辑如下:
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
实现方案
原有代码仅使用单次Dir扫描当前层级内容,可通过递归遍历子目录的方式实现全文件夹范围扫描,改造后逻辑可覆盖所有嵌套子文件夹内的目标文档。
改造核心逻辑
- 将单文件夹的文件扫描逻辑抽为可重复调用的通用过程
- 遍历当前路径下的所有文件、文件夹条目,自动跳过系统默认的当前目录(
.)、上级目录(..)占位条目 - 识别到文件夹条目时,自动进入该路径递归执行扫描
- 识别到后缀为doc、docx的文档时,执行打开、调用宏、保存、关闭的原有逻辑
改造后完整代码
' 宏启动入口,配置待扫描的根路径 Sub Aufruf() Dim rootPath As String ' 替换为你的目标根文件夹路径,末尾需保留反斜杠\ rootPath = "C:\Users\RHU\Desktop\VBA\" ' 启动全量递归扫描 ScanTargetFiles rootPath End Sub ' 递归遍历所有子文件夹的通用扫描过程 Sub ScanTargetFiles(currentPath As String) Dim entryName As String Dim fullPath As String ' 扫描当前路径下所有文件、文件夹条目 entryName = Dir(currentPath & "*", vbNormal + vbDirectory) Do While entryName <> "" ' 跳过系统占位的特殊目录条目 If entryName <> "." And entryName <> ".." Then fullPath = currentPath & entryName ' 判断当前条目属性为文件夹 If (GetAttr(fullPath) And vbDirectory) = vbDirectory Then ' 补充路径末尾反斜杠,递归扫描子文件夹 ScanTargetFiles fullPath & "\" Else ' 判断文件后缀为doc或docx,兼容大小写 If LCase(Right(entryName, 4)) = ".doc" Or LCase(Right(entryName, 5)) = ".docx" Then Documents.Open fileName:=fullPath ' 执行原有自定义宏逻辑 Call Datumsfelder ActiveDocument.Save ActiveDocument.Close End If End If End If ' 读取下一个目录条目 entryName = Dir() Loop End Sub
运行注意事项
- 运行宏前请关闭所有已打开的目标Word文档,避免文件占用导致保存失败
- 代码对文件后缀做了大小写兼容,不会因为doc/DOC、docx/DOCX的格式差异漏扫文件
- 如需跳过特定的缓存/临时文件夹,可在文件夹判断的分支中增加路径排除规则
内容的提问来源于stack exchange,提问作者rhuber
相关产品推荐
相关产品推荐

