These two lines connect to Word.  The EnsureDispatch makes sure Word constants 
work later:

>>> import win32com.client
>>> word = win32com.client.gencache.EnsureDispatch('Word.Application')

Then record a Word macro to do what you want (this was a find/replace all):

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "fox"
        .Replacement.Text = "cat"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

Then translate to Python:

>>> find = word.Selection.Find
>>> find.ClearFormatting()
>>> find.Replacement.ClearFormatting()
>>> find.Text = 'fox'
>>> find.Replacement.Text = 'cat'
>>> find.Forward = True
>>> find.Wrap = win32com.client.constants.wdFindContinue
>>> find.Execute(Replace=win32com.client.constants.wdReplaceAll)
True

-Mark



"URBAN LANDREMAN" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
  Good morning,

  I'm trying to write some Python code to programmatically do a Find and 
Replace of a string within a Microsoft Word document.
  Any suggestions on where I could look to find how to do such a function?

  Thank you.


  Urban Landreman 




------------------------------------------------------------------------------


  _______________________________________________
  Tutor maillist  -  [email protected]
  http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to