共用方式為


Workbook.BeforeClose 事件 (2007 系統)

更新:2007 年 11 月

在活頁簿關閉前發生。如果活頁簿已變更,則這個事件會在詢問使用者儲存變更前發生。

命名空間:  Microsoft.Office.Tools.Excel
組件:  Microsoft.Office.Tools.Excel.v9.0 (在 Microsoft.Office.Tools.Excel.v9.0.dll 中)

語法

Public Event BeforeClose As WorkbookEvents_BeforeCloseEventHandler

Dim instance As Workbook
Dim handler As WorkbookEvents_BeforeCloseEventHandler

AddHandler instance.BeforeClose, handler
public event WorkbookEvents_BeforeCloseEventHandler BeforeClose

範例

下列程式碼範例會示範 BeforeClose 事件的處理常式。如果活頁簿自上次儲存後已變更,下列程式碼便會提示使用者儲存變更、不儲存並更或取消關閉操作。如果使用者不儲存變更,則活頁簿的 Saved 屬性會設為 true,因此在執行關閉動作時,Microsoft Office Excel 不會提示使用者儲存活頁簿。如果使用者取消關閉動作,則 WorkbookEvents_BeforeCloseEventHandler 事件處理常式的 Cancel 參數設為 true,因此 Microsoft Office Excel 不會關閉活頁簿。

這是示範文件層級自訂的範例。

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
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;
        }
    }
}

使用權限

請參閱

參考

Workbook 類別

Workbook 成員

Microsoft.Office.Tools.Excel 命名空間