使用Excel VBA替换MS Word 10中的关键字

时间:2018-07-23 16:37:00

标签: excel vba excel-vba ms-word word-vba

我无法通过Excel VBA替换MS Word 10中的关键字。 我可以从Excel打开Word文档并找到目标关键字,但不能替换它们。看来我想念什么。

我的代码是:

Sub ReplaceValues()
Dim wApp As Object
Dim wDoc As Object
Set wApp = CreateObject("Word.Application")
wApp.Visible = True
wApp.Activate

Set wDoc = wApp.Documents.Add(Template:="C:\doc.docm", NewTemplate:=False, DocumentType:=0)

With wDoc
    .Application.Selection.Find.Clear.Formatting
    .Application.Selection.Find.Replacement.ClearFormatting
    .Application.Selection.Find.Text ="vGameName"
    .Application.Selection.Find.Replacement.Text = "vTest"
    .Application.Selection.Find.Forward = True
    .Application.Selection.Find.Wrap = wdFindContinue
    .Application.Selection.Find.Execute Replace>=wdReplaceAll
End With
End Sub

有人可以帮我吗?

谢谢

卡洛斯

2 个答案:

答案 0 :(得分:1)

看起来您没有引用正确的部分来开始替换:

With wDoc.ActiveDocument
    'Replaces in body, not in header/footer
    With .Content.Find
        .Execute FindText:="KeyWord", ReplaceWith:="Desire", Replace:=1
    End With
End With

答案 1 :(得分:1)

您使用的是已命名的Word常量,这些常量可通过早期绑定使用(并且需要将引用设置为Word库),但是使用“ Dim wApp As Object”和“ Dim wDoc As Object”意味着使用后期绑定。试试:

Sub ReplaceValues()
Dim wApp As Object, wDoc As Object, strFnd As String, strRep As String
Set wApp = CreateObject("Word.Application")
strFnd = "vGameName": strRep = "vTest"
With wApp
  .Visible = True
  Set wDoc = .Documents.Add("C:\doc.docm")
  With wDoc
    .Range.Find.Execute strFnd, , , , , , True, 1, , strRep, 2
  End With
End With
End Sub