Excel Guides

Running a Macro When a Worksheet is Deactivated in Excel

When a worksheet is deactivated in Excel, a macro can be run to perform certain actions. This can be useful if you want to run a macro when a user switches to another worksheet, or when a workbook is closed. To do this, you'll need to use the Workbook_Deactivate event.

The Workbook_Deactivate event occurs whenever a workbook is deactivated. This can happen when the user opens another workbook, or closes the current workbook. When this event occurs, the macro that is attached to it will run.

To attach a macro to the Workbook_Deactivate event, open the Visual Basic Editor (VBE) by pressing Alt+F11. Then, expand the list of modules on the left hand side and double click on the module that contains your macro. In the code window that appears, enter the following code:

Private Sub Workbook_Deactivate()

    ' Enter code here that will run when the workbook is deactivated.
End Sub

Replace the text "Enter code here that will run when the workbook is deactivated." with your own macro code. This code will now run every time the workbook is deactivated.

Move beyond 


Get started with Causal today.
Build models effortlessly, connect them directly to your data, and share them with interactive dashboards and beautiful visuals.