Philluminati
asked on
Automating an MS Word Mail Merge using C#
Below is a sniper of code from an application I'm writing in C#. I have added the Microsoft Office Word 11.0 Object Library and the TEMPLATE_FILENAME constant has a valid filename. However the code hangs on the statement
//Open Microsoft Word
Microsoft.Office.Interop.W
wordapp.Visible = false;
object filename = TEMPLATE_FILENAME;
object objTrue = true;
object objFalse = false;
object objMiss = Type.Missing;
Microsoft.Office.Interop.W
myMergeDocument = wordapp.Documents.Open(ref
myMergeDocument.Select();
//Microsoft.Office.Interop
// ON THE LINE BELOW: "COMException was unhandled." and "requested object is not available"
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
//myMergeDocument.Close();
wordapp.Visible = true;
wordapp.ShowMe();
return;
--------------
I have a word document that is set up with a mail merge source already and I just want to make it open and perform the merge. The merge source is a text file. The Open command doesn't seem to work correctly because the mail merge toolbar is disabled. Someone please help!!!
(I know how to use try catch blocks - i'm interested in fixing the problem...not just handling it gracely)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I have the same issue.
ASKER
I've solved my own question:
When the document is opened, the data source isn't opened (and just like the "Merge to Printer" toolbar option isn't available until you a merge source, so to, the code doesn't work until the data source has been opened.)
It's opened like this:
//Open the data source
object source = FILE_NAME;
object format = Microsoft.Office.Interop.W
myMergeDocument.MailMerge.
-------------------------
Now my code looks like this:
//Open Microsoft Word
Microsoft.Office.Interop.W
wordapp.Visible = false;
object filename = TEMPLATE_FILENAME;
object objTrue = true;
object objFalse = false;
object objMiss = Type.Missing;
Microsoft.Office.Interop.W
//Open the Template file
myMergeDocument = wordapp.Documents.Open(ref
myMergeDocument.Select();
//Open the data source
object format = Microsoft.Office.Interop.W
myMergeDocument.MailMerge.
//Perform the Mail Merge!!!
if (DIRECT_PRINT)
myMergeDocument.MailMerge.
else
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
myMergeDocument.MailMerge.
//Close the template document.
myMergeDocument.Close();
//Print the derived document.
wordapp.Visible = true;
wordapp.ShowMe();
return;
...and it works.
I've solved my own problem.
Phill