[英]Replacing string in Word document using Excel VBA
我有一个 .docx 模板,其中包含要使用 Excel VBA 替换的字符串(如序列号、日期、作者等)。
Private Sub Create()
Dim MaFeuille As Worksheet
Dim file As String
Set MaFeuille = Sheets("Information")
file = ActiveWorkbook.Path & "\" & "nomfichier.docx"
Set word_app = CreateObject("Word.Application")
With word_app
.Visible = True
.WindowState = wdWindowStateMaximize
End With
Set word_fichier = word_app.documents.Open(file)
word_app.Selection.Find.ClearFormatting
word_app.Selection.Find.Replacement.ClearFormatting
With word_app.Selection.Find
.Text = "blabla"
.Replacement.Text = "coucou"
End With
End Sub
Word 文件已启动,但未替换字符串。
始终声明所有变量,在模块顶部插入Option Explicit
以帮助您执行此操作。
您在Find
对象中缺少.Execute
,您还需要指定Replace
参数来执行替换(而不仅仅是查找)。
如果您是后期绑定,那么您不能使用 Word 库中存在的枚举,例如wdWindowStateMaximize
而不手动定义它,因此替代方法是直接提供值。
Option Explicit
Private Sub Create()
Dim MaFeuille As Worksheet
Set MaFeuille = Sheets("Information")
Dim file As String
file = ActiveWorkbook.Path & "\" & "nomfichier.docx"
Dim word_app As Object
Set word_app = CreateObject("Word.Application")
With word_app
.Visible = True
.WindowState = 1 'value for wdWindowStateMaximize
End With
Dim word_fichier As Object
Set word_fichier = word_app.Documents.Open(file)
With word_fichier.Range.Find
.Text = "blabla"
.Replacement.Text = "coucou"
.Execute Replace:=2 'value for wdReplaceAll
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.