var gWordApp:OLEVariant; procedure TfmLetters.LaunchWord; begin if VarIsEmpty(gWordApp) then begin try try gWordApp := GetActiveOLEObject('word.application'); except try gWordApp := CreateOLEObject('word.application'); except end; if VarIsEmpty(gWordApp) then gWordApp:=unassigned; end; except on EOLESysError do begin gWordApp := unassigned; end; end; end; end; function TfmLetters.PrintViaWord(const AWordDoc, ACSVFile:string; APrompt:boolean):boolean; var xBaseDoc, xAfterMergeDoc: OLEVariant; FGotDoc : boolean; begin result:=false; Screen.Cursor:=crHourglass; try // We need Microsoft Word to be running LaunchWord; if VarIsEmpty(gWordApp) then begin raise Exception.Create('Microsoft Word is not running.'); end; // Open document, perform the mail merge, print results, close and exit try gWordApp.Documents.Open(AWordDoc); FGotDoc:=true; except FGotDoc:=false; gWordApp:=unassigned; LaunchWord; end; Application.ProcessMessages; if VarIsEmpty(gWordApp) then begin raise Exception.Create('Microsoft Word is not running.'); end; if not FGotDoc then try gWordApp.Documents.Open(AWordDoc); except end; Application.ProcessMessages; // base doc is our 'template' document, we'll merge data into this to form a new doc xBaseDoc := gWordApp.ActiveDocument; try xBaseDoc.MailMerge.OpenDataSource( Name := ACSVFile, Format := wdOpenFormatText, ConfirmConversions := False, ReadOnly := True); except end; xBaseDoc.MailMerge.Destination := wdSendToNewDocument; xBaseDoc.Mailmerge.Execute(True); Application.ProcessMessages; // After a mail merge call as above, the active document is the one containing // the mail merged data - let's get a hand on that xAfterMergeDoc := gWordApp.ActiveDocument; gWordApp.WindowState := wdWindowStateMinimize; xBaseDoc.Close(SaveChanges := wdDoNotSaveChanges); // July 2016 - Office365 fix Sleep(2000); gWordApp.Visible:=true; // get Word to activate the merged doc, come to the fore etc xAfterMergeDoc.Activate; gWordApp.Activate; gWordApp.WindowState:=wdWindowStateNormal; Application.ProcessMessages; if APrompt then InfoDlg('You can preview, edit, save and print the documents in Word now.'#13#10#13#10+ 'Return here and click OK to continue when ready.'); result:=true; except on E:Exception do begin Error(Format('The following exception occurred;'#13#10+ '%s',[E.Message])); end; end; end;