Omer Cohen
Omer Cohen

Reputation: 141

how to check if closing the excel (workbook) vba

I'm looking for a code that can return a boolean 0,1 or true or false, so that it can recognise if someone closes the excel by clicking on X

Upvotes: 1

Views: 1101

Answers (1)

Matteo NNZ
Matteo NNZ

Reputation: 12695

Open the VBA Editor, then go on ThisWorkbook (in the project tree on the left-side of the IDE) and you will access the code of the workbook events.

Then, from the dropdown list on the right-top select the event BeforeClose after having selected the Workbook object in the left-top dropdown menu, and you will get the following code on the module:

Private Sub Workbook_BeforeClose(Cancel As Boolean)

End Sub

That macro will be called every time someone tries to close the Workbook. There, you can put a global variable to control the action, something like:

someoneIsClosing = True '<-- this is a globally defined variable
Cancel = True '<-- if you want to cancel the closing action
myMacro '<-- if you want to go back to "myMacro", i.e. any macro of your project and delegate it from handling the event.

Upvotes: 3

Related Questions