tags:

views:

51

answers:

2

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

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

David Stratton
Thanks. I ended up first checking myself if the file exists and then prompting a user using MessageBox.Show if they want to overwrite. Then, before I call WorkBook.SaveAs, I set DisplayAlerts = false else excel will try to throw it's own dialog. I set DisplayAlerts = true after the save.
Matthew Brown
+1  A: 

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!
}
sidewinderguy
I'll vote this one up.. It's my answer posted in the form of a code sample.
David Stratton