0

With the use of Python (win32com) I want to insert a user defined page number in a table cell of MS Word. Normally in Word if I want to have custom page number different from standard PAGE variable I press Cnrtl+F9 and insert field expression like this {={PAGE}+3}. So I want to get it in Python.

What I tried is inserting field in a table cell:

import win32com.client as win32
word = win32.Dispatch('Word.Application')
document = word.ActiveDocument

myRange = document.Paragraphs(1).Range
myTable = document.Tables.Add(myRange, 5, 5,
                          win32.constants.wdWord8TableBehavior)
cellRange = myTable.Cell(2, 2).Range    

myField = document.Fields.Add(
    cellRange,
    win32.constants.wdFieldEmpty,
    'PAGE',
    True)

In result I get this message:

" File "C:\Users\2E78~1\AppData\Local\Temp\gen_py\3.7\00020905-0000-0000-C000-000000000046x0x8x7\Fields.py", line 35, in Add , Type, Text, PreserveFormatting) pywintypes.com_error: (-2147352567, 'Error.', (0, 'Microsoft Word', 'This command is not available.', 'wdmain11.chm', 37373, -2146823683), None)"

P.S. I tried to record macro in Word to see VBA commands, but it seems to record very basic actions only.

7
  • it seems to record very basic actions only. It would be more accurate to say that the macro recorder doesn't use the Range object, as that isn't an object that can be manipulated by the user via the UI (unlike documents, windows, cells, tables, and fields etc.). Commented May 21, 2019 at 16:43
  • Perhaps try using one of the other Word wdFieldType constants; maybe wdFieldExpression or wdFieldPage? Alternatively, you could insert the field manually; then open the VBA editor and programmatically reading the field's Type property. Commented May 21, 2019 at 16:51
  • It's probably due to using the entire cell range as the target range - that would insert the field in the table cell structure, instead of into the cell. Try preceding the Fields.Add line with cellRange.Collapse win32.constants.wdCollapseStart Commented May 21, 2019 at 21:01
  • Your comments helped me both, I changed my code in this way: cellRange = myTable.Cell(2, 2).Range cellRange.Collapse(win32.constants.wdCollapseStart) myField = document.Fields.Add( cellRange, win32.constants.wdFieldPage, '', False) Commented May 22, 2019 at 16:07
  • What I can't get is how to create nested field like {={PAGE}+3}. If I simply set text or code of field like in this expression, Word recognizes brackets as a simple text, not as a field. Commented May 22, 2019 at 16:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.