Cassandra Durell
Cassandra Durell

Reputation: 101

How can I find and replace text in Word using Excel VBA?

I am using Excel VBA to open a document in Word. Once the document is open the goal is to search for "InsuranceCompanyName" and replace it with the company's name.

I have tried

wordDoc.Find.Execute FindText:="InsuranceCompanyName", ReplaceWith:="Fake Ins Co"

and

wordDoc.Replace What:="InsuranceCompanyName", Replacement:="Fake Ins Co"

and also

For Each myStoryRange In ActiveDocument.StoryRanges

    With myStoryRange.Find
        .Text = "InsuranceCompanyName"
        .Replacement.Text = "Fake Ins Co"
        .WrapText = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With 
Next myStoryRange

The full code is listed below.

Sub FindReplace()

Dim wordApp As Object 
Dim wordDoc As Object 
Dim myStoryRange As Range

'sets up the word app
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True 

'opens the document that we need to search through 
Set wordDoc = wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx")

'here is where the find and replace code would go

End Sub 

For the first method I get the error:

Object doesn't support this property or method.

For the second: the same error

The third method:

argument not optional

in regards to the .Find in

With myStoryRange.Find

Upvotes: 1

Views: 4470

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149325

Try this code

Option Explicit

Const wdReplaceAll = 2

Sub FindReplace()
    Dim wordApp As Object
    Dim wordDoc As Object
    Dim myStoryRange As Object

    '~~> Sets up the word app
    Set wordApp = CreateObject("Word.Application")
    wordApp.Visible = True

    '~~> Opens the document that we need to search through
    Set wordDoc = wordApp.Documents.Open("C:\Users\routs\Desktop\Sample.docx")

    For Each myStoryRange In wordDoc.StoryRanges
        With myStoryRange.Find
            .Text = "InsuranceCompanyName"
            .Replacement.Text = "Fake Ins Co"
            .Execute Replace:=wdReplaceAll
        End With
    Next myStoryRange
End Sub

In Action

enter image description here

Upvotes: 4

Related Questions