我正在使用 Excel VBA 宏將模板檔案中的單詞替換為 Excel 電子表格中的文本。格式很簡單;在 Excel 中,A 列有搜索詞,B 列有替換文本,而在 Word 中,檔案有{searchterm}占位符。我遍歷 Excel 作業表,在 A 和 B 中查找具有有效資料的行并找到替換。完整代碼:
On Error Resume Next
Set wApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Temp = Application.ActiveWorkbook.Path
Set wDoc = wApp.Documents.Open(Temp & "\Type some stuff.docx")
If wDoc Is Nothing Then
MsgBox "Could not find the template file at: " & Temp & "\Type some stuff.docx"
Exit Sub
End If
On Error Resume Next
wDoc.SaveAs Temp & "\Replaced some stuff.docx"
On Error GoTo 0
If wDoc Is Nothing Then
MsgBox "Could not save the word file at: " & Temp & "\Replaced some stuff.docx"
Exit Sub
End If
For R = 1 To LastR
ST = WS.Cells(R, 1)
RT = WS.Cells(R, 2)
'and if they are OK, use find/replace
If Len(ST) > 1 And Len(RT) > 1 Then
wDoc.Content.Find.Execute Wrap:=wdFindContinue, FindText:="{" & ST & "}", ReplaceWith:=RT, Replace:=wdReplaceAll
didSome = wDoc.Content.Find.found
End If
Next R
wDoc.Save
wDoc.Close
Set wApp = Nothing
所有值均有效:wDoc 是包含“This is something to change. {item1} Did this work.”的 word 檔案,ST 是“item1”,RT 是“替換第 1 項”。LastR 為 3。代碼貫穿所有行 - 它不會提前退出或任何其他內容。這將按預期創建檔案“New document.docx”,但文本尚未被替換。檢查didSome總是回傳 False。
我以 MS 的 Find.Execute 頁面為例,只更改了 Wrap。我錯過了什么?
uj5u.com熱心網友回復:
在將單詞物件定義為后期系結物件(使用 CreateObject 創建)時,您犯了一個典型的錯誤,即參考單詞列舉“wdFindContinue”。這意味著 wdFindContinue' 將具有值 0 而不是 wdFindWrap 列舉中定義的值 1。
因此,您要么需要將 wdFindContinue 替換為文字“1”,要么將 wdFindContinue 定義為值為 1 的常量,或者通過從 Tools.References 添加對 Word 物件的參考,更改為使用 Word 物件的早期系結參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/449934.html
