Home » excel » excel – Workbook_BeforeClose across Application

excel – Workbook_BeforeClose across Application

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have Workbook_BeforeClose in ‘This Workbook‘ of my addin, and when I open several workbooks in the same excel instance and try to close each one of them, Workbook_BeforeClose does not get called for each such workbook open in the instance but only for the final workbbook.

Is there anyway of making Workbook_BeforeClose called for all the workbooks in an excel instance, where I need to perform tasks at each work book close?

How to&Answers:

There are few steps to follow.

  1. create Class Module in your Excel IDE/VBA environment. Do it in one of the workbook which will be kept open until the end.

  2. change Class Module name into AppClass

  3. put this code inside AppClass module:

    Public WithEvents EXL As Application
    Private Sub EXL_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean)
        'sample msgbox
        MsgBox "You are about to close Workbook: " & Wb.Name
        'here your code
    End Sub
    
  4. In any standard module, like Module1, insert the following code:

    Public appEXL As New AppClass
    Sub Required_Initialization()
        'run it once or run it when this workbook is opened
        Set appEXL.EXL = Application
    End Sub
    
  5. Run the sub created in 4th step

  6. Do some tests: a) create new empty workbook and next try to close it. You will get MsgBox calling the name of the workbook you are about to close.

  7. Adjust as you need.

Important! Class are rather more difficult part of VBA programming. For better understanding try to search for any additional information in the web.

Answer:

KazJaw’s answer is a great idea.

I have an application-scoped addin using the technique he has outlined that has the following code in it:

Private Sub xlApp_WorkbookOpen(ByVal Wb As Excel.Workbook)

    On Error GoTo NoBookOpen:
        If Application.Calculation = xlCalculationManual And LCase(Left(ActiveWorkbook.Name, 6)) <> "export" Then
            If MsgBox("Calculation is set to Manual!" & vbCrLf & _
            "It will now be put back to Automatic", vbYesNo, "CALCULATION") = vbYes Then
                  Application.Calculation = xlCalculationAutomatic
            End If
        End If
NoBookOpen:

End Sub

This addin is present in all my instances of Excel but you could use Kazjaw’s idea and only load the add-in into specific instances of Excel.