开发者

Excel COMException 0x800A03EC when user cancels file overwrite

I have code that saves an excel file to a specific location and filename that cannot be changed by the user. It works fine when the file doesn't exist and saves silently. If the file does already exist and the user selects to overwrite it then it works fine as well. The problem occurs when it开发者_如何学编程 already exists and the user cancels the save. This causes the COMException 0x800A03EC to be thrown. Any ideas?

Reference: Microsoft Excel 12.0 Object Library

excelWorkbook.SaveAs(resultsFilePath, XlFileFormat.xlExcel8);


Put it in a Try/Catch block, as you should with any code that might fail? If it's in a try/catch block, then given the information you've given us, the design is flawed by definition, because....

  1. The ExcelWorkbook.Save() function is something you can't change. It is what it is...
  2. It's failing because the user canceled the save, and you're calling the SaveAs method without first checking for the existence of the file and if Excel prompts the user to give them the chance to cancel, and the only option is this error, then the only other option is to not give the user that choice.

As a general recommendation, I would say you should check for the existence of the file and give the user the chance to cancel in YOUR code. If they cancel, problem avoided. If they choose not to cancel, just delete the file before calling the Excel Save() function.

Alternately, you can instead use the SaveAs() function instead of Save(), and set the optional parameter named ConflictResolution to be XlSaveConflictResolution.xlLocalSessionChanges

(Just in case you ask, I know that dealing with optional parameters from C# is a pain, so check out this previous question for how to deal with those...)


How about this:

try
{
   excelWorkbook.SaveAs(resultsFilePath, XlFileFormat.xlExcel8);
}
catch // If you want, you can try and catch the actual exception here
{
   // If it gets here, the user probably cancelled (or something else
   // went wrong) You should handle those cases as needed. In the case
   // of the user cancelling, just do nothing here!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜