Paul Gransbergen

Paul Gransbergen

  • NA
  • 14
  • 2.8k

How to prevent MS Word Save As Dialog box from popping up?

Oct 23 2019 9:36 AM
Hi there,

I am trying to automate mailmerge from C# by opening a word-template (already bound to excel), refresh the link to excel and generate a result-document. This works fine, but the execution of the code gets interrupted when the template is closed, because the Word Save As File Dialog box pops up, waiting for one of the buttons to be clicked on. Obviously I don't want this, the template can be closed without saving, but the dialog box interrupts the program flow. My code looks like this:

this.Cursor = Cursors.WaitCursor;

Object oMissing = System.Reflection.Missing.Value;
Object oFalse = false;
String toetsbestand = @"C:\Import\BBS1001.xls";
String template = @"C:\Import\Template.docx";
String uitslag = @"C:\Import\Uitslag.docx";

Word.Application mailApp = new Word.Application();
mailApp.Visible = false;
mailApp.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
mailApp.Documents.Add(template);
mailApp.ActiveDocument.MailMerge.MainDocumentType = Word.WdMailMergeMainDocType.wdFormLetters;

mailApp.ActiveDocument.MailMerge.OpenDataSource(toetsbestand,
template, false, false, true,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, "SELECT * FROM 'BBS1001'",
ref oMissing, ref oMissing, Word.WdMergeSubType.wdMergeSubTypeOther);
mailApp.ActiveDocument.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
mailApp.ActiveDocument.MailMerge.Execute(Pause: false);
mailApp.ActiveDocument.SaveAs(uitslag);
mailApp.ActiveDocument.Close(SaveChanges: false);

GC.Collect();
GC.WaitForPendingFinalizers();

mailApp.Quit();

Marshal.ReleaseComObject(mailApp);

this.Cursor = Cursors.Default;
MessageBox.Show("Uitslag staat klaar!");

Does anyone have any idea how to prevent the Word Dialog Box from popping up? Any help will be greatly appreciated, thanx!

Answers (2)