View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
John Wilson John Wilson is offline
external usenet poster
 
Posts: 550
Default Automatically run a macro when opening an Excel file

Raphael,

Yes, you can run a macro just before the file is closed.
You'll need to use the Workbook_BeforeClose event.
From the VBA editor, double click on "ThisWorkbook"
in the "Projects" window and paste the following into
the pane on the right:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
' your macro here
End Sub

BUT!!!!!!!

It's probably not the "Close" event that you want.
Remember that when you open a workbook, you're
only placing a copy of that workbook into memory.
What you started with is still unchanged on your hard drive.
You can run your macros, do whatever you want but if you
close without saving, your saved copy doesn't change.
If you are saving and want to clear your stuff out, you
might want to use the Workbook_BeforeSave Event.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As
Boolean)
' your macro here
End Sub

John
"Raphael Saddy" wrote in message
...
Hi!

Thank you all for your quick answer! Really great!

Would it be possible to run a macro when the user
closes the file? I mean, when he closes the file, this
macro would run a code to undo everything that the
opening macro did.

Sorry not to have asked that before!

Thanks in advance.

Raphael

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!