Hi
Put your code in the Workbook_BeforeClose event proceedure.
Open the VBE (ALT+F11)
Double click ThisWorkbook in the project explorer window on the left hand
pane
from the left hand dropdown in the code pane (on the right of the window)
choose workbook
Select BeforeClose from the dropdown to the left
;-)