#native_company# #native_desc#

COM Functions to Mailmerge in Word XP

By Andy Hoyle
on September 18, 2002

Version: 1

Type: Sample Code (HOWTO)

Category: Other

License: GNU General Public License

Description: This script creates a Mailmerge Template, select a data source, then performs a mailmerge. I couldn’t find anything similar on the net in PHP so I had to write it myself (my least favorite option – much rather pinch someone elses code) mostly translated from a macro I recorded in VB.

This has taken me days to debug because word kept hanging which prevented me working with the files because they were locked.

// Author: Andy Hoyle						//
// Date: 18th Sep 2002						//
// Title: Script to create Mailmerge document and perform	//
// 						Mailmerge	//
// Version: 1.0							//
// Notes: This script works with Office XP Word on Windows 2000	//

//CONSTANTS USED (found using Object Browser in Microsoft Visual Basic Editor):
$wdFormLetters = 0;
$wdFieldMergeField = 59;
$wdFormatDocument = 0;
$wdSendToNewDocument = 0;

$word = new COM("word.application") or Die ("Did not connect");
$word->Visible = 1; // Doesn't do anything
$doc = $word->Documents->Add();
$doc->Mailmerge->MainDocumentType = $wdFormLetters;

$doc->Fields->Add($word->Selection->Range, $wdFieldMergeField, "Contact_Name");
$doc->Fields->Add($word->Selection->Range, $wdFieldMergeField, "City");
$doc->Fields->Add($word->Selection->Range, $wdFieldMergeField, "Address");
$doc->Fields->Add($word->Selection->Range, $wdFieldMergeField, "Postal_Code");
$doc->Fields->Add($word->Selection->Range, $wdFieldMergeField, "Country");

// Txt document must not have extension .txt or .dat (Word is very particular about
// what u call the file)
// This is my text document in c:tempdata.info
Contact_Name	Address	City	Postal_Code	Country
James Oliver	10 King St	Accrington	EX4 7BG	UK
Michaela Williams	10 The Coppice	Great Harwood	BB2 7QW	UK
Sharif Khan	10 Beardswood Ave	Blackburn	BB1 9PO	UK
Robbie Owen	34 Lord Square	London	LW3 9IY	UK


$doc->SaveAs("MergeTemplate.doc", $wdFormatDocument, False, "", False, "",
False, False, False, False, False);

$doc->Mailmerge->Destination = $wdSendToNewDocument;
$doc->Mailmerge->SuppressBlankLines = True;

// This tells in not to pause when executing mailmerge

// Save the merged document
$word->ActiveDocument->SaveAs("MergedDocument.doc", $wdFormatDocument, False, "",
True, "", False, False, False, False, False);

// This is the bit that gave me the most grief - for some reason, word insists
// on saving the mailmerge template after you perform a mailmerge
// if you dont do this it appears to hang (cause it normally
// display dialog box asking if u want to save before closing)

echo "End of script reached";