【问题标题】:Can't close word document after mailmerge邮件合并后无法关闭word文档
【发布时间】:2014-02-28 07:42:40
【问题描述】:

在我想关闭文件然后关闭 word 应用程序之后,我正在执行邮件合并。这是我执行邮件合并的地方

Application myWordApp = new Application();
Word.Document myWordDoc = new Word.Document();
myWordDoc = myWordApp.Documents.Add(ref fileDocTempl, ref oMissing, ref oTrue);
myWordApp.Visible = false;
Word.MailMerge wrdMailMerge = myWordDoc.MailMerge;
List<object> listTable = GetTableName();
const string cmdText = "Select * from [{0}]";
Object oQuery = string.Format(cmdText, listTable[0]);
wrdMailMerge.OpenDataSource(excelSource, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,oMissing, oMissing, oMissing, oMissing, oMissing, oQuery);
myWordApp.MailMergeAfterRecordMerge += myWordApp_MailMergeAfterRecordMerge;
myWordDoc.MailMerge.Execute(ref oFalse);

这是我关闭文件的地方

object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
myWordDoc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
myWordApp.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);

但是当我关闭 myWordDoc 时出现以下错误:

RPC_E_CALL_REJECTED COMexeption

只有在我进行大量邮件合并时才会发生这种情况,如果我尝试使用 50 一切正常,如果我尝试使用 2000 我会收到报告的错误。

【问题讨论】:

  • 将您的 2000 个列表拆分为 50 个记录的列表?
  • 我需要表演,而 2000 年只是程序要做的一小部分,它会合并 40 000 封邮件甚至更多,我认为拆分可能会降低表演
  • 这可能有点晚了,但是如果您可以使用 OpenXML 库而不是互操作,尤其是如果您希望它在无人值守的情况下运行。
  • 已解决:我刚刚杀死了进程!

标签: c# exception ms-word interop mailmerge


【解决方案1】:

一种可能的解决方法是将出现错误的块放在 while 循环中,并继续循环直到操作实际完成。

var ready = false;
var liCount = 0;
var pDelayBetweenRetry = 500;
var amountOfRetries = 10;
while(!ready)
{
  try
  {
    myWordDoc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
    ready = true;
  }
  catch (System.Runtime.InteropServices.COMException loE)
  {
    liCount++;
    if ((uint)loE.ErrorCode == 0x80010001)                      
    {
      // RPC_E_CALL_REJECTED - sleep half sec then try again
      System.Threading.Thread.Sleep(pDelayBetweenRetry);
    }
  }
  finally
  {
    if(liCount == amountOfRetries)
    {
      ready = true;
      //Write error to file or database so you can follow up it didn't worked out 
      //as planned
    }
  }
}

再说一遍;这是一种解决方法,这也意味着代码可能保留在循环内 ==> 异常继续被抛出 ==> 我添加了一个 finally 循环来捕获这种情况。

一些链接等:

http://msdn.microsoft.com/en-us/library/ms228772.aspx; is there a better way to handle RPC_E_CALL_REJECTED exceptions when doing visual studio automation?;

【讨论】:

    猜你喜欢
    • 2016-10-16
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多