簡體   English   中英

使用 Excel 在 Word 中查找和替換 VBA 不替換

[英]Find and replace in Word using Excel VBA doesn't replace

我正在使用 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 是一個 word 文檔,其中包含“這是要更改的內容。{item1} 是否有效。”,ST 是“item1”,RT 是“替換項目 1”。 LastR 是 3。代碼貫穿所有行 - 它不會提前退出或任何其他內容。 這將按預期創建文件“New document.docx”,但文本尚未被替換。 檢查didSome總是返回 False。

我從 MS 的 Find.Execute 頁面中拿了例子,只改變了 Wrap。 我錯過了什么?

在將單詞 object 定義為后期綁定 object(使用 CreateObject 創建)時,您犯了一個經典錯誤,即引用單詞枚舉“wdFindContinue”。 這意味着 wdFindContinue' 將具有值 0 而不是 wdFindWrap 枚舉中定義的值 1。

因此,您要么需要將 wdFindContinue 替換為文字“1”,要么將 wdFindContinue 定義為值為 1 的常量,或者通過從 Tools.References 添加對 Word Object 的引用,更改為對 Word object 使用早期綁定引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM