Run macro at closing of the workbook in Excel

For example, every time the user closes the WorkBook, I would like to ensure that certain Sheets are hidden, log out if logged in as admin and do some calculations and updates.

To do it in Excel, here is the answer:

  1. Option Explicit
  2. Private Sub WorkBook_BeforeClose(Cancel As Boolean)
  3. Call ResetMyWorkBook
  4. End Sub

a) The above macro code needs to be included under "ThisWorkBook" as shown below. When the WorkBook is closed, "WorkBook_BeforeClose" procedure is run which in turn calls "ResetMyWorkBook".

excel run macro at closing of the workbook

  1. Option Explicit
  2. Public Sub ResetMyWorkBook()
  3. 'Reset code goes here.
  4. End Sub

b) The custom "ResetMyWorkBook" macro code needs to be included under "Modules" as shown below.

excel run macro at closing of the workbook

 

You can find similar Excel Questions and Answer hereunder

1) How can I activate a routine when there is a change in value of a cell?

2) Converting numbers stored as text to numbers via macro in Excel

3) How do I assign a macro to a shape using VBA?

4) How to debug a macro in Excel VBA

5) I have a WorkBook that loads a form automatically when it is opened. In Excel, how can I suppress the form from loading on file open when required?

6) How can I prevent users from seeing / accessing my macro code?

7) How to enable or disable macros execution or loading in Excel

8) I frequently use a Macro - is there a way to quickly access the Macro using a Keyboard Shortcut?

9) How can I clear cell after activating a routine when there is a change in value of a cell?

10) I want to automatically run an initialization procedure whenever I open my WorkBook so that it is ready for use - how can I achieve that?

 

Here the previous and next chapter