简体   繁体   中英

Can't close word document after mailmerge

I am executing a mail merge after wich I want to close the file and then close the word application. this is where I execute the mail merge

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);

and this is where I close the files

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

but when I close the myWordDoc I get following error:

RPC_E_CALL_REJECTED COMexeption

this only happen if I do massive mail merge, If I try with 50 everything is ok, if I try with 2000 i get the reported error.

a possible workaround is to place the block where the error appears in a while loop and to continue the loop until the action actually completes.

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
    }
  }
}

Then again; this is a workaround and this also means there could be a possibility the code remains inside the loop ==> the exception keeps on to be thrown ==> I added a Finally loop to catch that occurance.

some links etc:

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? ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM