Events in Excel

Events are actions performed on any form or in an excel sheet. Open can be an event, Closing can be an event, right/left click can be an event etc. To explore more into events supported by excel, select a Workbook in the drop down menu in VBA. Beside Workbook drop down (refer the figure below), one can find various events supported in Excel.





workbook_open is a default event. This event is triggered when a workbook is open. An example of the same can be found here. The other events under in the drop down menu are
  • Sheetactivate
Private Sub Workbook_SheetActivate(ByVal Sh As Object)


End Sub
  • SheetBeforeDoubleClick : Event on Double click
  • SheetBeforeRightClick: Event on Right click
  • SheetBeforeClose: Event when Close button is clicked
  • SheetBeforeSave: Event when Save button is clicked
  • SheetBeforePrint: Event when Print button is clicked
 
To understand events in a better way, here is one example.
I have a open a workbook or an excel sheet. When I close this workbook, I should see a message, for example, "BYE BYE ... COME AGAIN". To accomplish this, I need to create a function linked to the event, BEFORECLOSE. When I select, BeforeClose in drop down menu, VBA automatically adds following piece of code.


  My work starts after this. Since, I have to display a message, I will add following lines in between the two lines i.e. Private sub workbook_beforeclose(Cancel as boolean) & End sub. 

Now, when I close my workbook, I get following message.



The format of the message box is msgbox([message],[buttons],[title]). Now, I have inserted following lines in between the to statements.






With these lines in place, if we close our excel sheet, we will see following message.

It can be seen, a message box with two buttons "Yes" and "No" together with title "Close" pops up. If we click on "Yes", Excel will close. In case, we click "No", Excel won't close.
Supported combination of buttons in Message box are vbYesNo, VbYesNoCancel, VbAbortRetryIgnore, VbOkOnly, VbokCancel, vbretrycancel etc.