Scalabium Software

SMReport Autogenerated
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

WordApp.Documents.Open(yourDocFileName);

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

WordApp.Selection.Find.ClearFormatting;
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

WordApp.ActiveDocument.SaveAs(yourDocFileName);

7. close MS Word instance

WordApp.ActiveDocument.Close;
WordApp.Quit;
WordApp := Unassigned;

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

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

var 
  WordApp: Variant;


Published: May 14, 2003

See also
 
DBISAM Password Recovery
Paradox Viewer
Paradox Password Recovery
Paradox ActiveX
MAPIMail
Metafile Convert
ABA Document Convert
Viewer for MS Outlook Messages
SMDBGrid
Paradox to MS Access converter
 
 


Contact to webmaster

 

Borland Software Code Gear Scalabium Delphi tips

Copyright© 1998-2024, Scalabium Software. All rights reserved.
webmaster@scalabium.com

SMExport advertising