简体   繁体   中英

Replace key words in MS Word 10 using Excel VBA

I'm failing in replacing key words in MS Word 10 via Excel VBA. I can open the Word document from Excel and find the target key words but not replace them. It seems that I'm missing something.

My code is:

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

Can anyone help me with this?

Thanks,

Carlos

Looks like you aren't referencing the correct sections to begin the replace:

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

You're using named Word constants, which are available with early binding (and require a reference to be set to the Word library), but your use of 'Dim wApp As Object' and 'Dim wDoc As Object' implies the use of late binding. Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM