Mega Code Archive

 
Categories / Delphi / Activex OLE
 

Automating MS Word using Ole

Title: Automating MS Word using Ole Question: How do I use MS Word to print some letters from within my Delphi application? Answer: I've used a version of the following code to create an object which lets me perform this operation very easily. Below the object definition code I have an example for how I use this object. ------------------------- Unit WordCls; Interface Uses SysUtils, COMObj, Dialogs; Type TWordObj = Class(TObject) Private WordApp: Variant; Public Constructor CreateObject(Visible: Boolean); Destructor Destroy; Override; Procedure FileOpen(FileName: String); Procedure MakeBig; Procedure MailMergeToDoc; Procedure FilePrintSetup(NewPrinter: String); Procedure FilePrint; Procedure FileClose; end; Implementation CONST wdDoNotSaveChanges = 0; wdSendToNewDocument = 0; wdWindowStateMaximize = 1; Constructor TWordObj.CreateObject(Visible: Boolean); begin Inherited Create; WordApp := CreateOleObject('Word.Application'); If not VarIsEmpty(WordApp) then WordApp.Visible := Visible; end; Destructor TWordObj.Destroy; Begin Try WordApp.Quit(wdDoNotSaveChanges); finally Inherited; end; end; Procedure TWordObj.FileOpen(FileName: String); Begin WordApp.Documents.Open(FileName); end; Procedure TWordObj.MakeBig; begin WordApp.WindowState := wdWindowStateMaximize END; Procedure TWordObj.MailMergeToDoc; Begin WordApp.ActiveDocument.MailMerge.Destination := wdSendToNewDocument; WordApp.ActiveDocument.MailMerge.Execute; end; Procedure TWordObj.FilePrintSetup(NewPrinter: String); Begin WordApp.ActivePrinter := NewPrinter; end; Procedure TWordObj.FilePrint; Begin WordApp.ActiveDocument.PrintOut(False); end; Procedure TWordObj.FileClose; Begin WordApp.Documents.Close(wdDoNotSaveChanges); end; end. ----------------------------- To use this object you do something like the following: Word := TWordObj.Create(True); //show what's happening Word.FileOpen('C:\My Documents\MyFile'); //open file Word.MailMergeToDoc; //do merge Word.FilePrint; //print merged document Word.FileClose; //close all files Word.Free; This will open a specific file in Word and display it. If you look in the VBA reference that comes with MS Office (you have to specifically install it - it's not part of the standard install) you'll see many other things you can do with MS Word. Once you have created the OLE connection to Word through the "WordApp := CreateOleObject('Word.Application');" statement, you have access to just about any of the VBA commands that are available inside Word.