Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Force replace macro apply on header also

I want to find & replace a text in word document. I created a macro as bellow.

Sub Macro1()
  ActiveDocument.Content.Find.Execute FindText:="#Text1", ReplaceWith:="acca", _
     Replace:=wdReplaceAll   
End Sub

It replaced all occurred but not in header/footer!! How forced to work on entire document include header/body/footer?

like image 424
Moh Tarvirdi Avatar asked Dec 21 '22 18:12

Moh Tarvirdi


1 Answers

I've always used this VBA code to Find/Replace, and it will do Headers/Footers along with the body of the document:

    Dim myStoryRange As Range


        For Each myStoryRange In ActiveDocument.StoryRanges
        With myStoryRange.Find
            .Text = "Text to find to replace goes here"
            .Replacement.Text = "And the replacement text goes here"
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll
        End With
        Do While Not (myStoryRange.NextStoryRange Is Nothing)
            Set myStoryRange = myStoryRange.NextStoryRange
            With myStoryRange.Find
                .Text = "Text to find to replace goes here"
                .Replacement.Text = "And the replacement text goes here"
                .Wrap = wdFindContinue
                .Execute Replace:=wdReplaceAll
            End With
        Loop
    Next myStoryRange

You can also copy and paste it a bunch of times in the same Sub to replace different strings at the same time.

like image 80
L. Miller Avatar answered Jan 02 '23 20:01

L. Miller