Python win32com - Automating Word - How to replace text in a text box?
Posted
by Greg
on Stack Overflow
See other posts from Stack Overflow
or by Greg
Published on 2010-06-11T13:00:11Z
Indexed on
2010/06/11
13:02 UTC
Read the original article
Hit count: 450
I'm trying to automate word to replace text in a word document using Python. (I'm on word 2003 if that matters and Python 2.4)
The first part of my replace method below works on everything except text in text boxes. The text just doesn't get selected. I notice when I go into Word manually and hit ctrl-A all of the text gets selected except for the text box.
Here's my code so far:
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) #select all
alltext.Find.Text = source
alltext.Find.Replacement.Text = target
alltext.Find.Execute(Replace=1,Forward=True)
#Special handling to do replace in text boxes
#http://word.tips.net/Pages/T003879_Updating_a_Field_in_a_Text_Box.html
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)
#My Usage
word=Word(visible=1,screenupdating=1)
word.open(r'C:\Invoice Automation\testTB.doc')
word.replace('[PGN]','1')
The for shp in self.app .. section is my attempt to hit the text boxes. It seems to find the text box, but it doesn't replace anything.
© Stack Overflow or respective owner