«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

How to replace text in a Word document


Here's how to use OLE automation for MS Word and replace some text string in any document.

use ActiveX, ComObj;

  wdFindContinue = 1;
  wdReplaceOne = 1;
  wdReplaceAll = 2;

  WordApp: Variant;

  // create OLE object for MS Word application:
  WordApp := CreateOLEObject('Word.Application');
  // load a document from your file
  WordApp.Selection.Find.Text := yourStringForSearch;
  WordApp.Selection.Find.Replacement.Text := yourNewStringForReplace;
  WordApp.Selection.Find.Forward := True;
  WordApp.Selection.Find.MatchAllWordForms := False;
  WordApp.Selection.Find.MatchCase := Flase;
  WordApp.Selection.Find.MatchWildcards := False;
  WordApp.Selection.Find.MatchSoundsLike := False;
  WordApp.Selection.Find.MatchWholeWord := False;
  WordApp.Selection.Find.MatchFuzzy := False;
  WordApp.Selection.Find.Wrap := wdFindContinue; 
  WordApp.Selection.Find.Format := False;
  WordApp.Selection.Find.Execute(Replace := wdReplaceAll)

To replace the first occurence of your text only use

WordApp.Selection.Find.Execute(Replace := wdReplaceOne);

Instead of

WordApp.Selection.Find.Execute(Replace := wdReplaceAll)

To check if text was found then use the Found method:

if WordApp.Selection.Find.Found then
  {do something}

Save the modified document with:


Finally, close the MS Word instance with:

WordApp := Unassigned;
If you want to change a font instead text, use the Font property of WordApp.Selection.Find.Replacement instead of Text.
Author: Shlomo Abuisak
Contributor: Shlomo Abuisak
Added: 2009-11-05
Last updated: 2009-11-05

« Return to contents »