How to open Word using OLE Automation

The CoApplication class defined in the type library represents the implementation of the Word Application interface. Call CoApplication.Create to create an instance of Word. This method will return a pointer to an interface of type _Application. The _Application interface provides a "Documents" interface which provides 2 methods to access documents: Add and Open.

Both these methods return a pointer to a _Document interface. As well these methods take parameters that are of type OLEVariant. Many parameters passed to Word methods are defined as "optional". Optional parameters must be included in calls to methods but can be defined as Unassigned to indicate that they are not being used. Delphi 4 provides a variable which can be used for optional parameters that are not being used called EmptyParam.

Sample Code

uses
  Word_TLB;

procedure StartWord(var WordApp: _Application; var WordDoc: _Document);
var
  SaveChanges: OleVariant;
begin
  try
    WordApp := CoApplication.Create;
    WordDoc := WordApp.Documents.Add(EmptyParam, EmptyParam);
    WordApp.Visible := True;
  except
   if Assigned(WordApp) then
   begin
     SaveChanges := wdDoNotSaveChanges;
     WordApp.Quit(SaveChanges, EmptyParam, EmptyParam);
   end;
end;