user7415328
user7415328

Reputation: 1083

Vba replace certain text in a word document?

I am using the below code to try and replace certain text in a Word document and save a copy as.

Here's my code:

Sub Macro1()
Dim app As Word.Application
Dim doc As Word.Document

    Set app = CreateObject("Word.Application")
    app.Visible = True
    Set doc = app.Documents.Open("G:\QUALITY ASSURANCE\03_AUDITS\PAI\templates\Audit Announcement Template.docx")


    With app.doc.Content.Find
            .Text = "Insert Date"
            .Replacement.Text = "Hello"
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll
        End With


    doc.SaveAs Filename:="G:\QUALITY ASSURANCE\03_AUDITS\PAI\templates\Audit Announcement Template2.doc", _
    FileFormat:=wdFormatDocument



    doc.Close
    app.Quit

End Sub

I get a compile error on this line:

With app.doc.Content.Find

Can someone please show me where I am going wrong?

Upvotes: 1

Views: 1971

Answers (1)

Alex K.
Alex K.

Reputation: 175936

Your With app.doc.Content.Find is not correct because doc is not a member of the app object, its a variable you have created.

Change to: With doc.Content.Find

As you open a .docx and you presumably want to save as such you need to:

doc.SaveAs Filename:="G:\path\file.docx", FileFormat:=WdSaveFormat.wdFormatDocumentDefault

You are early binding (via a reference) so no need for CreateObject() instead you can simply:

Set app = new Word.Application

Upvotes: 1

Related Questions