因为工作需要有个需求,就是要替换上百份word文档里的指定文字,网上找的软件只能免费替换几份文件,如果使用python又担心把word格式搞乱。这里我使用本地word来调用宏来实现替换,这样就不用担心格式会错乱了。示例代码实现了把呵呵替换成哈哈。
Sub ReplaceTextInAllDocxFiles()
' 设置根目录,这这里设置需要替换的目录
Dim rootFolderPath As String
rootFolderPath = "D:\test\"
' 调用递归函数
ReplaceTextInDocxFilesRecursive rootFolderPath
' 提示操作完成
MsgBox "替换完成!"
End Sub
Sub ReplaceTextInDocxFilesRecursive(folderPath As String)
Dim fso As Object
Dim folder As Object
Dim subfolder As Object
Dim file As Object
Dim wordApp As Object
Dim doc As Object
' 创建 FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' 创建 Word 应用程序对象
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = False ' 设置 Word 不可见
' 获取当前目录
Set folder = fso.GetFolder(folderPath)
' 循环处理当前目录下的所有文件,这里设置需要替换的文件后缀
For Each file In folder.Files
If LCase(Right(file.Name, 5)) = ".docx" Then
' 打开文档
Set doc = Documents.Open(file.Path)
' 替换文档中的文本这里设置需要替换的文档内容
With doc.Content.Find
.Text = "呵呵"
.Replacement.Text = "哈哈"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
' 保存并关闭文档
doc.Save
doc.Close
End If
Next file
' 循环处理当前目录下的所有子文件夹
For Each subfolder In folder.SubFolders
' 递归调用处理子文件夹
ReplaceTextInDocxFilesRecursive subfolder.Path
Next subfolder
' 关闭 Word 应用程序
wordApp.Quit
Set wordApp = Nothing
End Sub
文章评论