3

I am working to automate report generation using python. In a word document, I need to update the Form Fields to complete the report generation. On using win32.com.client.gencache.EnsureDispatch api, I am not able to get the formFields from the word document.

Following is the script written:

I am getting following error:

    raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
AttributeError: '<win32com.gen_py.Microsoft Word 16.0 Object Library.FormFields instance at 0x2217380698888>' object has no attribute '__getitem__'

I tried to search for the help on how to get the FormFields present in the word document but could not find any proper documentation on the error that I am getting.

word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible='False'
file = os.path.abspath(path)
d = word.Documents.Open(file)
d.FormFields[0].Result = reviewer

d.FormFields[0].Result should be a valid attribute.

on printing d, it is got to know that the object does not contain any FormFields at-all.

['CLSID', '__doc__', '__getattr__', '__init__', '__module__', '__repr__', '__setattr__', '_dispobj_', 'coclass_interfaces', 'coclass_sources', 'default_interface', 'default_source']
Ronak SHAH
  • 171
  • 2
  • 11

1 Answers1

1

Your variable d does not contain a Python object. It contains a thin Python wrapper around a COM object with a VBA interface.

Printing the dir of a Python object will show you its Python attributes. But FormFields is a VBA attribute of the COM object. Printing dir(d) will not show you the VBA attributes of the COM object.

But if there are forms in your document, you can see them like this:

>>> list (d.FormFields)

Look at your error message again. It says

AttributeError: '<win32com.gen_py.Microsoft Word 16.0 Object Library.FormFields instance at 0x2217380698888>' object has no attribute '__getitem__'

That error message confirms that the VBA object FormFields is a valid attribute and is actually present because the message gives a memory location for its Python wrapper.

Your problem is elsewhere. I suspect that FormFields does not contain what you expect. There must be something in it because otherwise you would get an IndexError, but you can check this as follows:

>>> d.FormFields.Count

If you want to know what the attributes of the COM object are, then look in the VBA documentation.

As a side note, at this stage as a beginner, you really should not be investing time in learning Python 2. Support for Python 2 ceases at the end of this year. Some of us have no choice but to go on working in Python 2, but if you have a choice, switch, and soon.

BoarGules
  • 16,440
  • 2
  • 27
  • 44