Scalabium Software

SMExport advertising
Knowledge for your independence'.
Home Delphi and C++Builder tips

#152: Replace text/font in doc-file

Today I want to show how use an OLE automation for MS Word and replace some text string in any document.

1. you must create OLE object for MS Word application:

WordApp := CreateOLEObject('Word.Application');

2. you must load a document from your file


3. you must specify all parameters for find/replace - text string, range etc

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;

If you want to change a font instead text, use Font property of WordApp.Selection.Find.Replacement instead Text
In such manner you may set a red background for all 'Adam Smith' strings, for example

4. start a find/replace process

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

or replace a first occur only:

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

5. if you want to check if text was found then use Found method:

if WordApp.Selection.Find.Found then
  <do something>

6. save a modified document


7. close MS Word instance

WordApp := Unassigned;

All what you need is to add ActiveX, ComObj units in use-clause and declare such consts and variables:

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

  WordApp: Variant;

Published: May 14, 2003

See also
SMMsg suite
DBISAM Password Recovery
ABA Database Convert
dBase Viewer
Metafile Convert
Paradox ActiveX
Database Information Manager
Paradox Viewer
Paradox to MS Access converter

Contact to webmaster


Borland Software Code Gear Scalabium Delphi tips

Copyright© 1998-2018, Scalabium Software. All rights reserved.

SMExport advertising