Partager via


WorkbookBase.BeforeClose Event

Definition

Occurs before the workbook closes. If the workbook has been changed, this event occurs before the user is asked to save changes.

public:
 event Microsoft::Office::Interop::Excel::WorkbookEvents_BeforeCloseEventHandler ^ BeforeClose;
public event Microsoft.Office.Interop.Excel.WorkbookEvents_BeforeCloseEventHandler BeforeClose;
member this.BeforeClose : Microsoft.Office.Interop.Excel.WorkbookEvents_BeforeCloseEventHandler 
Public Custom Event BeforeClose As WorkbookEvents_BeforeCloseEventHandler 

Event Type

Examples

The following code example demonstrates a handler for the BeforeClose event. The event handler prompts the user to either save changes, not save changes, or cancel the close operation if changes have been made to the workbook since it was last saved. If the user does not save changes, then the Saved property of the workbook is set to true so that Microsoft Office Excel does not prompt the user to save the workbook when the close operation continues. If the user cancels the close operation, then the Cancel parameter of the WorkbookEvents_BeforeCloseEventHandler event handler is set to true so that Microsoft Office Excel does not close the workbook.

This example is for a document-level customization.

private void WorkbookBeforeClose()
{
    this.BeforeClose +=
        new Excel.WorkbookEvents_BeforeCloseEventHandler(
        ThisWorkbook_BeforeClose);
}

void ThisWorkbook_BeforeClose(ref bool Cancel)
{
    if (!this.Saved)
    {
        DialogResult result = MessageBox.Show("Do you want to save the " +
            "changes you made to " + this.Name + "?", "Example",
            MessageBoxButtons.YesNoCancel);

        switch (result)
        {
            case DialogResult.Yes:
                this.Save();
                break;

            case DialogResult.Cancel:
                Cancel = true;
                break;

            // The following code ensures that the default Save File 
            // dialog is not displayed.
            case DialogResult.No:
                this.Saved = true;
                break;
        }
    }
}
Sub ThisWorkbook_BeforeClose(ByRef Cancel As Boolean) _
    Handles Me.BeforeClose

    If Not Me.Saved Then
        Dim result As DialogResult = _
            MessageBox.Show("Do you want to save the " & _
            "changes you made to " & Me.Name & "?", _
            "Example", MessageBoxButtons.YesNoCancel)

        Select Case result
            Case DialogResult.Yes
                Me.Save()
            Case DialogResult.Cancel
                Cancel = True
                ' The following code ensures that the default Save File 
                ' dialog is not displayed.
            Case DialogResult.No
                Me.Saved = True
        End Select
    End If
End Sub

Applies to