我有一個帶有字串的 .docx 模板,我想用另一個模板替換它(如序列號、日期、作者等)。我想為此使用 excel,我撰寫了該代碼,但我不知道為什么它不起作用
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
編輯:單詞檔案已啟動,但未替換字串
uj5u.com熱心網友回復:
始終宣告所有變數,插入
Option Explicit模塊頂部以幫助您執行此操作。.Execute您在物件中缺少Find,您還需要指定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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/451402.html
下一篇:資料透視表-添加總計的百分比
