I am trying to automate a word to replace text in a text document using Python. (I'm on the word 2003, if that matters, and Python 2.4)
The first part of my replacement method below works in everything except text in text fields. The text is simply not selectable. I notice that when I enter Word manually and press ctrl-A, all the text is selected except the text field.
Here is my code:
class Word:
def __init__(self,visible=0,screenupdating=0):
pythoncom.CoInitialize()
self.app=gencache.EnsureDispatch(WORD)
self.app.Visible = visible
self.app.DisplayAlerts = 0
self.app.ScreenUpdating = screenupdating
print 'Starting word'
def open(self,doc):
self.opendoc=os.path.basename(doc)
self.app.Documents.Open(FileName=doc)
def replace(self,source,target):
if target=='':target=' '
alltext=self.app.Documents(self.opendoc).Range(Start=0,End=self.app.Documents(self.opendoc).Characters.Count)
alltext.Find.Text = source
alltext.Find.Replacement.Text = target
alltext.Find.Execute(Replace=1,Forward=True)
for shp in self.app.Documents(self.opendoc).Shapes:
if shp.TextFrame.HasText:
shp.TextFrame.TextRange.Find.Text = source
shp.TextFrame.TextRange.Find.Replacement.Text = target
shp.TextFrame.TextRange.Find.Execute(Replace=1,Forward=True)
word=Word(visible=1,screenupdating=1)
word.open(r'C:\Invoice Automation\testTB.doc')
word.replace('[PGN]','1')
For shp in self.app .. section is my attempt to get into text fields. It seems to find the text box, but does not replace anything.
source
share