Hide template Word Doc while displaying executed Word Doc?

1.2k views Asked by At

In my code below, I start up 2 word instances. One instance I set to my "template", the file for a Mail Merge document that hasn't been run. The other Instance is for a blank document I will use to copy/paste each page from the executed mail merge document into, and then individually save the document.

I make both Word instances visible, then open up my "template" and the blank document for individual saving using each instance. Next I open the Data Source for the MailMerge operation.

Once I Execute the Mail Merge operation, I am left with 3 documents visible on my screen:

  1. The original "template" for the Mail Merge
  2. The blank document I was using for individual file saving when copy/pasting the Mail Merge sections.
  3. The executed mail merge document titled "Form Letters1".

My code processes a while() loop going through and copies each section of "Form Letters1" and pasting it into my document titled "NewDocument.doc". My foreach() loop then updates a database tracking table before generating the filename of "NewDocument.doc" and saving it.

Once the individual section from "Form Letters1" has been saved, I select everything in the newly saved document and clear it out for processing the next section in "Form Letters1".

When all individual sections of "Form Letters1" have been copy/pasted and saved as their own document I hide my "NewDocument.doc" with oNewWord.Visible = false;.

My issue here is that on screen I am still showing both the the "template" document for the Mail Merge, and also the "Form Letters1" executed Mail Merge document.

Is there any way for me to hide the template and keep "Form Letters1" visible? I tried setting oWord.Visible = false; before my message box appears, but that hides both the "template" AND "Form Letters1" (the executed Mail Merge document I need to let users review and print).

public void MergeSplitAndReview()
    {
        try
        {
            //MergeDocLibrary mdl = new MergeDocLibrary();
            //mdl.mergeDocument(docSource, docLoc);

            // Mail Merge Template
            Word.Application oWord = new Word.Application();
            Word.Document oWrdDoc = new Word.Document();
            // New Document Instance
            Word.Application oNewWord = new Word.Application();
            Word.Document oNewWrdDoc = new Word.Document();

            object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

            // Documents must be visible for code to Activate()
            oWord.Visible = true;
            oNewWord.Visible = true;

            Object oTemplatePath = docLoc;
            Object oMissing = System.Reflection.Missing.Value;

            // Open Mail Merge Template
            oWrdDoc = oWord.Documents.Open(oTemplatePath);

            // Open New Document (Empty)
            // Note: I tried programmatically starting a new word document instead of opening an exisitng "blank",
            //       bu when the copy/paste operation occurred, formatting was way off. The blank document below was
            //       generated by taking a copy of the FullMailMerge.doc, clearing it out, and saving it, thus providing
            //       a kind of formatted "template".
            string newDocument = projectDirectory + "\\NewDocument.doc";
            oNewWrdDoc = oNewWord.Documents.Open(newDocument);

            // Open Mail Merge Datasource
            oWrdDoc.MailMerge.OpenDataSource(docSource, oMissing, oMissing, oMissing,
               oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

            // Execute Mail Merge (Opens Completed Mail Merge Documents Titled "Letters1")
            oWrdDoc.MailMerge.Execute();

            // Save the processed Mail Merge Document for Archiving
            // oWord.ActiveDocument.SaveAs2(docTempDir + "FullMailMerge.doc");

            int docCnt = oWord.ActiveDocument.Sections.Count - 1;
            int cnt = 0;
            while (cnt != docCnt)
            {
                cnt++;
                string newFilename = "";

                // Copy Desired Section from Mail Merge
                oWord.ActiveDocument.Sections[cnt].Range.Copy();
                // Set focus to the New Word Doc instance
                oNewWord.Activate();
                // Paste copied range to New Word Doc
                oNewWord.ActiveDocument.Range(0, 0).Paste();

                foreach (ListViewItem lvI in lvData.Items)
                {
                    if (lvI.Checked) // Get first checked lvI in lvData to use for generating filename
                    {
                        updateAddrChngHistory(lvI.SubItems[16].Text);

                        string fileSys = lvI.SubItems[12].Text.ToUpper();
                        string memNo = lvI.SubItems[0].Text;

                        newFilename = fileSys + "%" + memNo + "%" + "" + "%" + "" + "%" + "CORRESPONDENCE%OUTGOING - ACKNOWLEDGEMENT%" + DateTime.Now.ToString("yyyy-MM-dd-hh.mm.ss.ffffff") + ".doc";

                        lvI.Remove(); // Delete from listview the lvI used for newFilename
                        break;        // Break out of foreach loop
                    }
                }

                // Save New Word Doc
                oNewWord.ActiveDocument.SaveAs2(docTempDir + newFilename);
                // Clear New Word Doc
                oNewWord.ActiveDocument.Content.Select();
                oNewWord.Selection.TypeBackspace();
            }
            // Show only the Full Mail Merge Doc. Have user press OK when finished to close documents.
            // Set 'False' in PROD, 'True' in DEV
            // oWord.Visible = false;
            // Hides my new word instance used to save each individual section of the full Mail Merge Doc
            oNewWord.Visible = false;
            MessageBox.Show(new Form() { TopMost = true }, "Click OK when finsihed.");

            oNewWord.ActiveDocument.Close(doNotSaveChanges); // Close the Individual Record Document
            oNewWord.Quit();                                 // Close Word Instance for Individual Record
            oWord.ActiveDocument.Close(doNotSaveChanges);    // Close the Full Mail Merge Document (Currently ALSO closes the Template document)
            oWord.Quit(doNotSaveChanges);                    // Close the Mail Merge Template
            MessageBox.Show("Mail Merge Completed, Individual Documents Saved, Instances Closed.");
        }
        catch (Exception ex)
        {
            LogException(ex);
            MessageBox.Show("Source:\t" + ex.Source + "\nMessage: \t" + ex.Message + "\nData:\t" + ex.Data);
            // Close all Word processes
            Process[] processes = Process.GetProcessesByName("winword");
            foreach (var process in processes)
            {
                process.Close();
            }
        }
        finally
        {

        }
    }
1

There are 1 answers

1
AudioBubble On

You should be able to show/hide individual documents using, e.g.the equivalent of the following VBA:

oWord.ActiveDocument.Windows(1).Visible = false

(substituting the appropriate document object instead of ActiveDocument).