我正在编写一个能大量使用Excel的程序。在执行"退出"命令时,我似乎遇到了一个障碍。它不仅会关闭它创建的所有excel实例(这是为了防止任何事情被挂起),还会关闭任何在程序之外手动打开的excel实例。
有人能指出我在这方面的错误吗?
(此外,我正在学习C#,所以请原谅任何"常见"错误。欢迎所有建设性的批评。)
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);
}
}
保留应用程序创建的工作簿的列表,然后让您的"退出"关闭这些工作簿。如果最后一个工作簿关闭,而Excel还有0个剩余工作簿,则也关闭Excel,否则保持打开状态,手动工作簿仍然可用。