How to detect when a workbook is closing?

后端 未结 6 2365
后悔当初
后悔当初 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 14:01

    This seems to work Code in the WorkBook

    Public ByeBye As String
    
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
       ByeBye = "BB @ " & Now()
    End Sub
    
    Private Sub Workbook_Deactivate()
       If Left(ByeBye, 2) = "BB" Then
          ByeBye="Done"
          MsgBox "Closing"
       Else
          ByeBye="Done"
          MsgBox "DeActivating BUT NOT Closing"
       End If
    End Sub
    
    Private Sub Workbook_Open()
       ByeBye = "OP @ " & Now()
    End Sub
    

    Just uses a public variable ByeBye

    • You must initialise it in WorkBook.Open
    • You must Set it in WorkBook.BeforeClose

    and can test it in WorkBook.DeActivate

    In case it is needed for this to work even after a VBA crash - and loss of ByeBye value I'm resetting it in the Workbook_SheetChange and in WorkBook_SheetSelectionChange

    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
       ByeBye = "SC @ " & Now()
    End Sub
    
    Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
       ByeBye = "SSC @ " & Now()
    End Sub
    

    The above addendum is really only needed if you were going to use the string default of "" for the tested value - but I'm using "BB @ " & Now() so this is not really needed

提交回复
热议问题