VBA代码:替换Word文档中指定内容
以下是一个VBA代码示例,它可以将Word文档中指定段落中的内容替换为'123':
Sub ReplaceTextInWordDoc()
Dim wdApp As Object
Dim wdDoc As Object
Dim rng As Object
' 创建 Word 应用程序对象
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True ' 如果希望看到替换的过程,请将此行注释掉
' 打开 Word 文档
Set wdDoc = wdApp.Documents.Open("C:\路径\你的文档.docx") ' 替换为你的 Word 文档路径
' 定义要替换的内容及替换后的内容
Dim findText As String
Dim replaceText As String
findText = "审计了后附的贵公司提供的"
replaceText = "123"
' 遍历每个段落,查找并替换指定内容
For Each rng In wdDoc.Range.Paragraphs
With rng.Range
If InStr(1, .Text, findText) > 0 And InStr(1, .Text, "竣工财务决算报表") > 0 Then
.Text = Replace(.Text, findText & Mid(.Text, InStr(1, .Text, findText) + Len(findText), InStr(1, .Text, "竣工财务决算报表") - InStr(1, .Text, findText) - Len(findText)), replaceText)
End If
End With
Next rng
' 保存并关闭 Word 文档
wdDoc.Save
wdDoc.Close
' 释放对象
Set rng = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
在上面的代码中,你需要将'C:\路径\你的文档.docx'替换为你的Word文档的实际路径。运行该VBA程序后,它将会在指定段落中将'审计了后附的贵公司提供的'与'竣工财务决算报表'之间的内容替换为'123'。请注意,该程序会直接修改你的Word文档,请确保提前备份你的文档,以防止意外情况。
原文地址: https://www.cveoy.top/t/topic/bOaP 著作权归作者所有。请勿转载和采集!