user1651460
user1651460

Reputation: 450

Find/replace texts in Word document footer using Excel VBA

I want to replace some tags in my Word document. My current solution does not implement the replacement/search at the document footer.

The word template I am using has 2 different footers (first page is different to second page footer). I want to change something in the footer of the second page.

'replacement regarding CHAPTER 1
For CurRow = Tabelle2.Range("C2") To Tabelle2.Range("C3")
    If Tabelle2.Range("B" & CurRow).Value = "x" Then
        ReplacementTextF = "<<TagToBeFound>>"
        ReplacementText = "I am a customer"
        dataObjectLongText.SetText ReplacementText
        dataObjectLongText.PutInClipboard       'Copy to clipboard
        With WordDoc.Content.Find
            .Execute FindText:=ReplacementTextF, ReplaceWith:="^c", Replace:=2, Wrap:=wdFindContinue    'Paste from clipboard
        End With

Until here, everything works as it should. It finds all texts and replace them using the clipboard (because the replacement text is often greater than 255 characters).

To take a look into the footer I tried this right after the code above:

        With WordDoc.Sections(1).Footers(1).Range.Find
            .Execute FindText:=ReplacementTextF, ReplaceWith:="^c", Replace:=2, Wrap:=wdFindContinue    'Paste from clipboard
        End With

I tried several solutions. This is my last approach. I referenced the Word object library.

Upvotes: 1

Views: 282

Answers (1)

macropod
macropod

Reputation: 13515

As it appears you're using late binding, you can't simply employ a Word constant like wdFindContinue; you need to either declare it or use its numerical equivalent. Other complications can arise if a previous Find/Replace used wildcards and/or formatting for the Find or Replace arguments, so it's wise to reset these. Try:

With WordDoc.Sections(1).Footers(1).Range.Find '1 = wdHeaderFooterPrimary
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = ReplacementTextF
  .Replacement.Text = "^c"    'Paste from clipboard
  .Wrap = 1 'wdFindContinue
  .MatchWildcards = False
  .Execute Replace:=2 'wdReplaceAll
End With

or:

With ActiveDocument.StoryRanges(9).Find '9 = wdPrimaryFooterStory
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = ReplacementTextF
  .Replacement.Text = "^c"    'Paste from clipboard
  .MatchWildcards = False
  .Wrap = 1 'wdFindContinue
  .Execute Replace:=2 'wdReplaceAll
End With

In any event, since it appears the footer is to display the same content as you're replacing ReplacementTextF in the document body with, you might do better to assign a unique Style name to whatever ReplacementTextF is, then reference that Style via a STYLEREF field in the footer. Do this in the template. That way, you'd obviate the need for a Find/Replace in the footer.

Upvotes: 1

Related Questions