How to save multiple Excel apps using .net and C#

S

sclarke18

Hi, I am trying to automate saving and closing multiple Excel applications ie
save and close each one, one by one using .net and C#. Ine one running of
the code, I have been able to get the code to save and close the first app,
but not the second, third, etc. Although each time I run the code (from
start to finish) it correctly refereces the next one and saves and closes it
correctly. Also I have tried using workbooks.close and application.Quit
instead of theprocess.Kill() but it doesn't seem to make a difference.

My code is as below, so any ideas, suggestions, would be appreciated:

redoa:
//Get reference to Excel application
Excel.Application oExcelApp =
(Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

Process[] processlist = Process.GetProcessesByName("Excel"); //Show number
of running Excel apps
foreach (Process theprocess in processlist) //Get each process in turn
{

if (oExcelApp.Workbooks.Count >= 0) //If more than 0 workbooks in app
{
foreach (Excel.Workbook wkb in oExcelApp.Application.Workbooks)
{ //Specify path to save file
Object oSaveAsFileExcel1 = @"C:\" + wkb.Name;

//Save each workbook
wkb.SaveAs(oSaveAsFileExcel1, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
Excel.XlSaveAsAccessMode.xlNoChange,
XlSaveConflictResolution.xlLocalSessionChanges,
true, Type.Missing, Type.Missing, Type.Missing);
}
oExcelApp.Workbooks.Close();
theprocess.Kill(); //Kill the current application
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcelApp);
//Release the application
GC.Collect(); //Garbage collect

}

//Check if Excel is still open and redo if there are
int echeck1 = System.Diagnostics.Process.GetProcessesByName("Excel").Length;
if (echeck1 != 0) goto redoa;

return;

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top