How to detect when a workbook is closing?

后端 未结 6 2363
后悔当初
后悔当初 2021-02-15 13:12

The Workbook.BeforeClose event triggers when the workbook is about to close but before the saving message prompt which allows cancelling it.

How can I detect when the wo

6条回答
  •  孤独总比滥情好
    2021-02-15 13:55

    This is an evolution of my 1st Answer - it detects the edge case problem by comparing the ActiveWindow.Caption against ThisWorkbook.Name so it can detect that issue and deal with it. It's not the most elegant solution but I believe it works.

    All Code in the Workbook most of it in DeActivate

    Public ByeBye As String
    
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
       ByeBye = "B4C"
    End Sub
    
    Private Sub Workbook_Deactivate()
       If ByeBye = "B4C" Then
          If ActiveWindow.Caption = ThisWorkbook.Name Then
             If ThisWorkbook.Saved Then
                MsgBox "No problem - Closing after Saving"
             Else
                MsgBox "No problem - Closing without Saving"
             End If
          Else
             If ThisWorkbook.Saved Then
                MsgBox "No problem - New Workbook Activation"
             Else
                MsgBox "Oops Try Again You Cannot Activate '" & ActiveWindow.Caption & "' until '" & ThisWorkbook.Name & "' has completed processing & IT HAS NOW COMPLETED", vbOKOnly, "Hiding"
                ThisWorkbook.Activate
             End If
          End If
       Else
          MsgBox "No problem - Just Hiding"
       End If
       ByeBye = "Done"
    End Sub
    
    Private Sub Workbook_Open()
       ByeBye = "OPENED"
    End Sub
    

    In response to comment about saving I tested this for 7 possible combinations as follows

     1) Closing without Edits - No Saving Involved ... MsgBox Prompted with ... No problem - Closing after Saving       
     2) Not closing - Just Switch Workbook - Whether Edited or Not ... MsgBox Prompted with ... No problem - Just Hiding        
     3) Not closing - Switch Workbook - After Edit & Cancel ... MsgBox Prompted with ... Oops Try Again …       
     4) Closing and saving ... MsgBox Prompted with ... No problem - Closing after Saving       
     5) Closing and Saving after a prior Cancel ... MsgBox Prompted with ... No problem - Closing after Saving      
     6) Closing but Not Saving ... MsgBox Prompted with ... No problem - Closing without Saving         
     7) Closing but not Saving after a prior Cancel ... MsgBox Prompted with ... No problem - Closing without Saving        
    

提交回复
热议问题