DEV Community

Andrews
Andrews

Posted on • Originally published at geekexcel.com on

How to Run a Macro Automatically Before Workbook Close in Excel?

In this article, you will learn how to run a Macro automatically before a Workbook closes in Excel Office 365. Let’s see them below!! Get the official version of MS Excel from the following link: https://www.microsoft.com/en-in/microsoft-365/excel

Auto Run Macro When Workbook Closes

  • To run macro as the workbook closes , you have to use Workbook Event Workbook_BeforeClose.
  • The syntax of this event is given below.
Private Sub Workbook_BeforeClose(Cancel As Boolean)

 'Your Code here.

End Sub

Enter fullscreen mode Exit fullscreen mode
  • Firstly, in the Excel Worksheet, you have to go to the Developer Tab.
  • Then, you need to ** ** select the Visual Basic option under the Code section.

Select Visual Basics

  • Now, in project explorer , you have to find ThisWorkbook object in project explorer and double-click on it.

find ThisWorkbook object

  • After that, you have to copy and paste the code given below.
 Private Sub Workbook_BeforeClose(Cancel As Boolean)
 ThisWorkbook.Save
MsgBox "This Workbook is saved."

End Sub

Enter fullscreen mode Exit fullscreen mode
  • You need to save the code by selecting it and then close the window.

Save the code

  • Again, you have to go to the Excel Spreadsheet , and click on the Developer Tab.
  • You need to choose the Macros option in the Code section.

Choose Macro option

  • Now, you have to close the Excel Worksheet.
  • Finally, your workbook will be automatically saved , and the message will be shown as given below.

Workbook Saved

Verdict

From this chapter, you can get some clarification about how to run a Macro automatically before a Workbook closes in Excel Office 365. Let me know if you have any doubts regarding this article or any other Excel/VBA topic.

Thank you so much for visiting Geek Excel!! *If you want to learn more helpful formulas, check out Excel Formulas *!!

Read Ahead:

Top comments (0)