2

I am trying to use pywin32 to open a Word document and copy the values from some text boxes and just print them out. The code and error are below. Any help greatly appreciated. I have looked far and long with no answers to this probably simple question.

import win32com.client as win32

word = win32.gencache.EnsureDispatch('Word.Application')
word.Visible = 0
doc = word.Documents.Open('C:/testdoc.docm')
question2 = ActiveDocument.Variables("txtQuestion02").Value

print question2

Traceback (most recent call last): File "C:/Users/rjudge/SkyDrive/Programming/SAP Assignment grading/Grade MS Word - Doc version.py", line 18, in question2 = ActiveDocument.Variables("txtQuestion02").Value NameError: name 'ActiveDocument' is not defined

Most recent errors after Bernie's suggestion: Traceback (most recent call last): File "C:/Users/Robert/SkyDrive/Programming/SAP Assignment grading/Grade MS Word - Doc version.py", line 18, in question2 = word.ActiveDocument.Variables("txtQuestion02").Value

File "C:\Python27\lib\site-packages\win32com\client__init__.py", line 463, in getattr return self.ApplyTypes(*args)

File "C:\Python27\lib\site-packages\win32com\client__init__.py", line 456, in ApplyTypes self.oleobj.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args), pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Word', u'Object has been deleted.', u'C:\Program Files (x86)\Microsoft Office\Office12\1033\WDMAIN11.CHM', 25305, -2146822463), None)

Process finished with exit code 1

Way in which txtQuestion02 is set in Word (VBA code for the textbox):

`

Private Sub txtQuestion02_Change()

Me.txtAnswer02.Value = Me.txtQuestion02.Value

End Sub `

The variable does show it has the correct value when I look at local variables and it does immediately change whenever I change what is in the textbox. The txtQuestion02.value does seem to be doing what it is supposed to do. I just can't seem to access using pywin32. Right now I am going down a terrible road of printing out to text where I can manipulate it with python. But that is just plain wrong.

1 Answer 1

0

ActiveDocument has not been defined in your code, but it has been defined as an instance of the Document class within the Word application (called word in your code sample). Try instead:

question2 = word.ActiveDocument.Variables("txtQuestion02").Value 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the try, but that did not fix it. There is a different set of errors:
You're most welcome. Please edit your question to show how you are setting the "txtQuestion02" variable in the macro-enabled document.

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.