Activex OLE Delphi

Title: Calling MS Word to do a Mail Merge
Question: This procedure provides an easy way to call Microsoft Word from Delphi to do a "mail merge" of an existing Word template file and data file.
Answer:
procedure DoMSWordMerge(template_file, data_file: String; see_Word,
auto_print: Boolean);
{Arguments: template_file: path and name of existing MS Word template merge file
data_file: existing merge data file (must have a file extension
recognized by MS Word)
see_Word: set to True if you want user to be able to see Word
auto_print: set to True if you want result document to print
automatically and Word to exit
As written this code requires that the Word2000.PAS file be referenced in the
Uses section. To compile with the Word97.PAS file simply change the OpenOld
method call to "Open" and the PrintOutOld call to "PrintOut". Also requires
ComObj and ActiveX in the Uses section. }
var
MSWord: _Application;
MSDoc: _Document;
Unknown: IUnknown;
OLEResult: HResult;
OLEvar: OleVariant;
begin
OLEResult := GetActiveObject(CLASS_WordApplication, nil, Unknown);
if (OLEResult = MK_E_UNAVAILABLE) then
MSWord := CoWordApplication.Create //get MS Word running
else begin
OleCheck(OLEResult); //check for errors
OleCheck(Unknown.QueryInterface(_Application, MSWord));
end;
MSWord.Visible := see_Word; //let user see Word running
OLEvar := template_file; //merge template document
MSDoc := MSWord.Documents.OpenOld(OLEvar, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam);
MSDoc.MailMerge.OpenDataSource(data_file, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam);
OLEvar := False;
with MSDoc.MailMerge do begin
Destination := wdSendToNewDocument;
Datasource.FirstRecord := wdDefaultFirstRecord;
Datasource.LastRecord := Integer(wdDefaultLastRecord);
Execute(OLEvar); //do merge into new document
end;
MSDoc.Close(EmptyParam, EmptyParam, EmptyParam); //close template document
OLEvar := 1;
MSDoc := MSWord.Documents.item(OLEvar); //attach to the merge result document
{The next 4 lines cause Word to print the merged document and then exit. If
removed, Word will remain active without printing the merge document and
control will return to the Delphi program. User will have to print the
document by hand themselves.}
if auto_print then begin
OLEvar := False; //implies wait for printing to complete
MSDoc.PrintOutOld(OLEvar, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam);
OLEvar := wdDoNotSaveChanges; //don't save the merge document
MSWord.Quit(OLEvar, EmptyParam, EmptyParam);
end;
MSDoc := nil;
MSWord := nil;
end;