呼叫被被叫方拒绝了。 (来自HRESULT的异常:0x80010001(RPC_E_CALL_REJECTED))

时间:2013-12-17 16:05:31

标签: c# automation ms-word office-interop mailmerge

我有一个小的C#Winforms应用程序,它使用Word.Interop获取单个邮件合并文档,复制每个部分,将该部分粘贴到它自己的文档中,然后单独保存。

Error

我保留(有时是随机)收到错误消息:Call was rejected by callee. (Exception from HRESULT: 0x80010001 (RPC_E_CALL_REJECTED))。我测试了下面的代码,当我使用断点时,我从未收到过这条消息。但是,如果我让它不受限制地运行,那么我的第oNewWord.ActiveDocument.Range(0, 0).Paste();行似乎就出错了。什么是更奇怪的,有时我得到预期的消息,其他时候处理似乎只是挂起,当我在Visual Studio中按PAUSE时,它显示我当前在我的异常消息框行。

任何人都知道如何解决这个问题?

CODE:

public void MergeSplitAndReview()
        {
            try
            {
                // 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();

                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(); // THIS IS THE POINT WHERE I GET THE ERROR MENTIONED WHEN NOT USING A BREAKPOINT.



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

                            string fileSys = lvI.SubItems[14].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();
                }
                // 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 finished.");
                MessageBox.Show(new Form() { TopMost = true }, "Click OK when finished.");

                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.Documents.Open(docTempDir + "FullMailMerge.doc");

                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
            {

            }
        }

2 个答案:

答案 0 :(得分:2)

正如Andrew Barber指出,处理异常时,我的方式导致性能损失

the article引用的Hans Passant确实为选项3提供了 GREAT 方式。

----以下会导致性能下降

当它很忙时,需要在一段时间后重试。

此功能可能有助于重试

使用lambda(委托)作为参数

用法1

var selectionLocal = selection; 
var range = RunWithOutRejected(() => selectionLocal.Range);

用法2

RunWithOutRejected(
   () =>
       following.Value.Range.FormattedText.HighlightColorIndex =
         WdColorIndex.wdGray25);

用法3

var nameLocal = name;
var bookmark = RunWithOutRejected(() =>  
   winWordControl
   .GetDocument()
   .Bookmarks.Add(nameLocal, range));
name = RunWithOutRejected(() => bookmark.Name);
return new KeyValuePair(name, bookmark);

ps:当使用此函数互操作MSword时,代码_application.Selection.PasteSpecial();失败


    public static T RunWithOutRejected<T>(Func<T> func)
    {
        var result = default(T);
        bool hasException;

        do
        {
            try
            {
                result = func();
                hasException = false;
            }
            catch (COMException e)
            {
                if (e.ErrorCode == -2147418111)
                {
                    hasException = true;
                }
                else
                {
                    throw;
                }
            }
            catch (Exception)
            {
                throw;
            }
        } while (hasException);

        return result;
    }
}

答案 1 :(得分:0)

我从办公室2010升级到办公室2016(赢得10 64位)后遇到了同样的问题, 我的问题:单词不是编辑文档的默认程序,所以 我从“控制面板\所有控制面板项目\默认程序\设置默认程序”中将单词作为默认程序 它解决了。