I have created an Excel VSTO Addin which will show a message box with yes, no and cancel as button options on the close event of Current document.
I have opened 2 excel documents to edit. After I complete my edit I try to close one of them, when I click on document close button my message box will appear. If I click on "No" then all the changes should be discarded and the document should be closed. Other documents should not be closed.
This is the code I used on Don't save action
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.WorkbookBeforeClose += Application_WorkbookBeforeClose;
}
private void Application_WorkbookBeforeClose(Excel.Workbook Wb, ref bool Cancel)
{
DialogResult result = MessageBox.Show("Do you want to save changes to " + Wb.Name + "?", "Microsoft Excel ", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
switch (result)
{
case DialogResult.Yes:
Wb.Save();
break;
case DialogResult.No:
int count = this.Application.Workbooks.Count;
if(count > 0)
{
if (count == 1)
{
Excel.Application excel =Globals.ThisAddIn.Application;
Workbooks workbooks = excel.Workbooks;
foreach (Workbook wb in workbooks)
{
wb.Close(false, missing, missing);
}
workbooks = null;
excel.Quit();
excel = null;
}
else
{
Wb.Close(false, missing, missing);
}
}
break;
case DialogResult.Cancel:
Cancel = true;
break;
}
}
If morethan one excel document is opened for edit, then Excel vsto addin should close the particular excel docuemnent in which the close actions is performed and other documents should remain opened. My method closes the document but not closing the application. How to close the Excel Application completely? my excel appear like this