电波码农 - 一个个人日记本

  • 首页
  • 人工智能
  • 建站
  • 取证
  • 编程
  • 电磁
  • 物联网
  • 杂项
  1. 首页
  2. 编程
  3. 正文

批量替换word文档里的指定文字

2024年2月28日

因为工作需要有个需求,就是要替换上百份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

相关文章:

无线电安全的好书 中华人民共和国无线电频率划分规定
标签: 暂无
最后更新:2024年3月1日

editor

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

近期文章

  • VSCode去掉注释和空行
  • 宝塔面板wordpress搬家
  • 宝塔面板申请https
  • 批量替换word文档里的指定文字
  • 中华人民共和国无线电频率划分规定

近期评论

  1. Area 52? 发表在 宝塔面板wordpress搬家
  2. 2mGDwGPVvLLSVnohtW5EBbAvSgJ 发表在 Linux VPS 快速搭建属于自己的 WordPress 网站以及“数据库创建失败,请检查是否存在同名数据库”报错处理

分类

  • 人工智能
  • 取证
  • 建站
  • 杂项
  • 物联网
  • 电磁
  • 编程

https wordpress 宝塔面板 建站 搬家

2025 年 8 月
一 二 三 四 五 六 日
 123
45678910
11121314151617
18192021222324
25262728293031
« 3 月    

COPYRIGHT © 2024 电波码农. 网站地图

Theme Kratos Made By Seaton Jiang