1. Home
  2. Computing & Technology
  3. Delphi Programming

How do I (using Delphi) talk to Microsoft Word?

By Zarko Gajic, About.com

Microsoft Word is an Automation server, which is a particular type of COM server application. Automation servers can be controlled either by talking directly to the COM interface defined by the application, or by using a Variant to talk (implicitly) to the IDispatch interface supported by the application.

To automation Word with a Variant variable (supported since Delphi 2), you initialise the Variant with a call to CreateOleObject (from the ComObj unit). Then, the Variant acts just like the object exposed by the utomation server. You can call methods and access properties, so long as you know what they are. When Word is installed, there is an optional VBA help file that can be installed as well, which describes all the functionality supported by the Word Automation object(s).

Automation through a Variant allows optional parameters to be omitted, where you are happy with their default values. So, if you are automating Microsoft Word, and you wish to save a document to disk you can call the SaveAs method of the document object, and ignore most of the eleven arameters that it takes, as shown below

More info: Delphi takes control

~~~~~~~~~~~~~~~~~~~~~~~~~
uses
   ComObj;

procedure TForm1.Button1Click(Sender: TObject) ;
var
   WordApplication, WordDocument: Variant;
begin
   WordApplication := CreateOleObject('Word.Application') ;
   WordDocument := WordApplication.Documents.Add;
   WordApplication.Selection.TypeText('Hello world') ;
   WordDocument.SaveAs(FileName := 'C:\Doc.Doc',
                       AddToRecentFiles := False) ;
   WordApplication.Quit(False)
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Where are the Office '97 components in Delphi 7?
« PREVIOUS TIP

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2003 Delphi Tips
  7. How do I (using Delphi) talk to Microsoft Word?

©2009 About.com, a part of The New York Times Company.

All rights reserved.