2

I'm trying to edit header of a MS Word document that has existing header using win32com.
I tried this to edit page header:

import win32com.client as win32

word = win32.gencache.EnsureDispatch('Word.Application')
doc=word.Documents.Open("C:\\a.docx")
word.Visible = True
word.ActiveDocument.Sections[0].Headers[win32.constants.wdHeaderFooterPrimary].Range.Text='test text'
word.ActiveDocument.Save()
doc.Close(False)
word.Application.Quit()

But it has no effect (header didn't changed at all)!!
What is the correct way to edit MS Word header via win32com ?

Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • 2
    Brave soul... Have you considered the indexes? At least in macros and C# they are 1-based, not 0-based. You should be able to get a header by integer index as well. I've only dealt with Word through C# and VB so I'm not sure this is relevant – Sten Petrov Jan 03 '13 at 22:52
  • I think Sten Petrov may be right. It's been a while since I used `win32com`, but in general neither it nor VB does anything clever with indices; the VB interface is 1-based because the underlying `IDispatch` interface is, and therefore so is the `win32com` interface. – abarnert Jan 03 '13 at 23:01

1 Answers1

4

Use parentheses instead of square brackets in this line, along with 1-based indexing. Everything in COM is a function call or property.

word.ActiveDocument.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range.Text='test text'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251