closures程序而不closuresExcel的单独实例

我正在编写一个与Excel大量工作的程序。 执行退出命令时,我似乎遇到了麻烦。 它不仅会closures它创build的所有excel实例(这是在任何情况下悬而未决的情况下),而且还会closures任何通过程序手动打开的excel实例。

任何人都可以指出我的错在哪里呢?

(另外,我正在学C#,所以请原谅任何“常见”的错误,欢迎所有build设性的批评。)

private void BtnExit_Click_1(object sender, EventArgs e) { try { if (ObjApp == null) { Excel.Application ObjApp = new Excel.Application(); } Modules.MessageUpdate(this, ObjApp, EH, 5, 22, "", "", "", 0, 0, 0, 0, "Application Quit.", "N"); ObjApp.Quit(); if (ObjApp != null) { ObjApp = null; } if (UC != null) { UC = null; } if (Zoho != null) { Zoho = null; } if (Modules != null) { Modules = null; } if (EH != null) { EH = null; } if (proc != null) { proc = null; } if (Wait != null) { Wait.Close(); Wait = null; } GC.Collect(); GC.WaitForPendingFinalizers(); Environment.Exit(0); } catch(COMException) { //System.Windows.Forms.Application.Restart(); if (ObjApp != null) { ObjApp = null; } if (UC != null) { UC = null; } if (Zoho != null) { Zoho = null; } if (Modules != null) { Modules = null; } if (EH != null) { EH = null; } if (proc != null) { proc = null; } if (Wait != null) { Wait.Close(); Wait = null; } //ObjApp.Quit(); GC.Collect(); GC.WaitForPendingFinalizers(); Environment.Exit(0); } catch { if (ObjApp != null) { ObjApp = null; } if (UC != null) { UC = null; } if (Zoho != null) { Zoho = null; } if (Modules != null) { Modules = null; } if (EH != null) { EH = null; } if (proc != null) { proc = null; } if (Wait != null) { Wait.Close(); Wait = null; } GC.Collect(); GC.WaitForPendingFinalizers(); Environment.Exit(0); } } 

保留应用程序创build的工作簿列表,然后让您的“退出”closures这些工作簿。 如果最后一个工作簿closures,并且Excel有剩余的工作簿,则还要closuresExcel,否则请保持打开状态,使手动工作簿仍然可用。