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.