Hennetier Nicolas
Hennetier Nicolas

Reputation: 43

Find and Replace text within headers with Win32COM

I'd like to find some words in the headers of a Word document and replace them with other words : I've done this in the body of the document with the following code, and it works fine.

import win32com.client

wdFindContinue = 1
wdReplaceAll = 2        
app = win32com.client.DispatchEx("Word.Application")
app.Visible = 1
app.DisplayAlerts = 0
app.Documents.Open(document_path)

FromTo = {"<#TITLE#>":"My title", "<#DATE#>":"Today"}

for From in FromTo.keys():
        app.Selection.Find.Execute(From, False, False, False, False, False, True, wdFindContinue, False, FromTo[From], wdReplaceAll)

The problem is that this code doesn't work for headers and footers. I've also tried this :

app.ActiveDocument.Sections(1).Headers(win32com.client.constants.wdHeaderFooterPrimary).Range.Select
app.Selection.Find.Execute(From, False, False, False, False, False, True, wdFindContinue, False, FromTo[From], wdReplaceAll)

But it doesn't work better (despite the fact that I don't have any error message).

Does someone have an idea on how to do that? Another information is that I have an image inserted in the headers as well, I don't know if it matters or not.

Upvotes: 2

Views: 1650

Answers (1)

Ivan.s
Ivan.s

Reputation: 144

You must activate header/footer pane after open document. Language Visual basic. Change syntax to python

   ActiveDocument.ActiveWindow.Panes(1).View.SeekView=wdSeekCurrentPageHeader

for header and

ActiveDocument.ActiveWindow.Panes(1).View.SeekView = wdSeekCurrentPageFooter

for footer

Then search/replace

To change pane to main part use

ActiveDocument.ActiveWindow.Panes(1).View.SeekView = wdSeekMainDocument

Upvotes: 2

Related Questions