Vba excel workbook событие open

vba events

Often when working with Excel files we want to introduce certain features which are supposed to be fired in the circumstance of certain events. Say we have a Excel worksheet that is time-sensitive, that needs to be updated based on some web-resource or database. Should we hope that the user will leverage our Refresh button. Fortunately Microsoft introduced Excel Workbook Events – events which are fired in very specific situation in reaction to user interaction. This

Introduction

Excel VBA Events such as the VBA Open Workbook event are very useful in organizing your Workbooks functionality and ease of use. Although VBA events have many advantages, be aware of one significant setback – whenever a VBA Event is fired VBA Code is executed! So? Isn’t that the point? Of course but that has some repercussions – as Excel (and other MS Office Applications) delete the Undo/Redo stack of events once VBA code is executed. This means that whenever a VBA Macro is executed the user will not be able to undo any previous changes to the Workbook using i.e. CTRL+Z.
VBA Events
Therefore be sure to limit your VBA Event handlers to the bare minimum as you may find users annoyed instead of impressed with your Excel GUI.

The VBA Open Workbook and other Workbook events are fired whenever an event in scope of the entire Workbook happens. This can include Activating, Saving, Opening or Closing the Workbook.

Adding Workbook Events

Let’s learn how to add Workbook events:

Select the Workbook module

Select the Workbook module from your Project – VBAProject window as shown below.
Workbook Events: Select Workbook module

Select Workbook from the Object list

To view all available events associated with your Workbook select the Workbook value from the Object list in the Code window. This should automatically include the VBA Open Workbook event into your Workbook module.
Workbook Events: Select Workbook from Object list

Select the desired event from the available list of events

By selecting the Workbook Object from the previous list you will now have access to the available list of events associated with your Workbook. Simply select the desired VBA event from the list and the code will be added automatically.
Workbook Events: Select Workbook Event

List of Workbook Events (VBA Open Workbook etc.)

Below is a complete list of VBA Workbook Events available from Excel:

Event Name Descriptions
ActivateEvent Workbook is activated
AddinInstall Workbook is installed as an add-in
AddinUninstall Workbook is uninstalled as an add-in
AfterSave Workbook is saved
AfterXmlExport Excel saves or exports data from the workbook to an XML data file
AfterXmlImport An existing XML data connection is refreshed or after new XML data is imported into the workbook
BeforeClose Before the workbook closes. If the workbook has been changed, this event occurs before the user is asked to save changes
BeforePrint Before the workbook (or anything in it) is printed
BeforeSave Before the workbook is saved
BeforeXmlExport Before Excel saves or exports data from the workbook to an XML data file
BeforeXmlImport Before an existing XML data connection is refreshed or before new XML data is imported into the workbook
Deactivate Workbook is deactivated
New New workbook is created
NewChart New chart is created in the workbook
NewSheet New sheet is created in the workbook
Open Workbook is opened
PivotTableCloseConnection After a PivotTable report closes the connection to its data source
PivotTableOpenConnection After a PivotTable report opens the connection to its data source
RowsetComplete The user navigates through the recordset or invokes the rowset action on an OLAP PivotTable
SheetActivate When any sheet is activated.
SheetBeforeDoubleClick When any worksheet is double-clicked, before the default double-click action.
SheetBeforeRightClick When any worksheet is right-clicked, before the default right-click action.
SheetCalculate After any worksheet is recalculated or after any changed data is plotted on a chart
SheetChange When cells in any worksheet are changed by the user or by an external link.
SheetDeactivate When any sheet is deactivated
SheetFollowHyperlink When you click any hyperlink in a workbook
SheetPivotTableAfterValueChange After a cell or range of cells inside a PivotTable are edited or recalculated (for cells that contain formulas)
SheetPivotTableBeforeAllocateChanges Before changes are applied to a PivotTable
SheetPivotTableBeforeCommitChanges Before changes are committed against the OLAP data source for a PivotTable
SheetPivotTableBeforeDiscardChanges Before changes to a PivotTable are discarded
SheetPivotTableChangeSync After changes to a PivotTable
SheetPivotTableUpdate After the sheet of a PivotTable report has been updated
SheetSelectionChange When the selection changes on any worksheet. Does not occur if the selection is on a chart sheet
Shutdown When the workbook host item shuts down
Startup After the workbook is running and all the initialization code in the assembly has been run
SyncEvent When the local copy of a worksheet that is part of a Document Workspace is synchronized with the copy on the server
WindowActivate When any workbook window is activated
WindowDeactivate When any workbook window is deactivated
WindowResize When any workbook window is resized

Worksheet VBA Events

Adding Worksheet Events

The VBA Open Workbook and other Workbook events are fired whenever an event in scope of the entire Workbook happens. This can include Activating, Saving, Opening or Closing the Workbook.

Adding Workbook Events

Let’s learn how to add Worksheet events:

Select a Worksheet module

Select the Worksheet module from your Project – VBAProject window as shown below. Be sure to select the Worksheet in which you want to add the event handler!:
Worksheet VBA Events: Select a Worksheet module

Select Worksheet from the Object list

To view all available events associated with your Worksheet select the Worksheet value from the Object list in the Code window. This should automatically include the VBA SelectedChange Worksheet event into your Worksheet module.
Worksheet VBA Events: Select the Worksheet object

Select the desired event from the available list of events

Worksheet VBA Events: Select the desired Worksheet VBA Event

By selecting the Worksheet Object from the previous list you will now have access to the available list of events associated with your Worksheet. Simply select the desired VBA event from the list and the code will be added automatically.

List of Worksheet Events

Event Name Descriptions
Activate When a workbook, worksheet, chart sheet, or embedded chart is activated.
BeforeDelete
BeforeDoubleClick When a worksheet is double-clicked, before the default double-click action.
BeforeRightClick When a worksheet is right-clicked, before the default right-click action.
Calculate After the worksheet is recalculated, for the Worksheet object.
Change When cells on the worksheet are changed by the user or by an external link.
Deactivate When the chart, worksheet, or workbook is deactivated.
FollowHyperlink When you click any hyperlink on a worksheet. For application- and workbook-level events, see theSheetFollowHyperlink event and SheetFollowHyperlink event.
LensGalleryRenderComplete When a callout gallery’s icons (dynamic & static) have completed rendering.
PivotTableAfterValueChange After a cell or range of cells inside a PivotTable are edited or recalculated (for cells that contain formulas).
PivotTableBeforeAllocateChanges Before changes are applied to a PivotTable.
PivotTableBeforeCommitChanges Before changes are committed against the OLAP data source for a PivotTable.
PivotTableBeforeDiscardChanges Before changes to a PivotTable are discarded.
PivotTableChangeSync After changes to a PivotTable.
PivotTableUpdate After a PivotTable report is updated on a worksheet.
SelectionChange When the selection changes on a worksheet.
TableUpdate After a Query table connected to the Data Model is updated on a worksheet.

Chart VBA Events

Adding Chart Events

Let’s learn how to add Chart events:

Select a Chart module

Select the Chart module from your Project – VBAProject window as shown below. Be sure to select the Chart to which you want to add the event handler!:
Chart VBA Events: Select Chart module

Select Chart from the Object list

To view all available events associated with your Chart select the Chart value from the Object list in the Code window. This should automatically include the VBA Activate Chart event into your Chart module.
Chart VBA Events: Select Chart Object

Select the desired event from the available list of events

Chart VBA Events: Select Chart Event

By selecting the Chart Object from the previous list you will now have access to the available list of events associated with your Chaet. Simply select the desired VBA event from the list and the code will be added automatically.

List of Chart Events

Event Name Descriptions
Activate chart sheet, or embedded chart is activated.
BeforeDoubleClick when a chart element is double-clicked, before the default double-click action.
BeforeRightClick when a chart element is right-clicked, before the default right-click action.
Calculate after the chart plots new or changed data, for the Chart object.
Deactivate when the chart, worksheet, or workbook is deactivated.
MouseDown when a mouse button is pressed while the pointer is over a chart.
MouseMove when the position of the mouse pointer changes over a chart.
MouseUp when a mouse button is released while the pointer is over a chart.
Resize when the chart is resized.
Select when a chart element is selected.
SeriesChange when the user changes the value of a chart data point by clicking a bar in the chart and dragging the top edge up or down thus changing the value of the data point.

Use Cases

I decided to list some interesting examples of Workbook VBA events usage:

  • Before save notification – if you don’t want to overwrite your current file version you may want to override the BeforeSave Workbook VBA event to add an additional prompt to confirm if you want to overwrite your current file. Code below:
    Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
        Cancel = (MsgBox("Are you sure?", vbYesNo, "Question") = vbNo)
    End Sub
    
  • Refresh all PivotTables and QueryTables on VBA Open Workbook Event – if you want to make sure your Pivot Tables are up to date whenever someone opens your Workbooks add a simple piece of code:
    Private Sub Workbook_Open()
        ActiveWorkbook.RefreshAll
    End Sub
  • Prevent Changes to certain Cells – say you want to prompt a user when changing a certain cell value and revert to a default value otherwise. Simply override the VBA Change Event as follows:
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target = Range("A1") And Target.Value <> 100 Then
           If MsgBox("Are you sure you want to change this cell?", vbYesNo) = vbNo Then
                'Revert Target value
                Application.EnableEvents = False
                Target.Value = 100
                Application.EnableEvents = True
            End If
        End If
    End Sub

VBA Excel Workbook_Open Event

Excel predefines some popular actions that  you would do on different Objects (worksheet, workbook, button, etc), those actions are called Event. For example, activating a worksheet is an Event, closing a workbook is an Event, clicking on a button is an event. Each Object has its own list of Events, Workbook has a list of Events (e.g. close workbook, open workbook), worksheet has a list of Events (e.g. activate worksheet, edit a Cell).

If you perform an Event, say, closing a workbook, your desired code can be triggered. For example, you may want to save a workbook automatically when you close a workbook, or you may want a welcome message box to pop up when a workbook is opened. Event is a Sub Procedure (begin with Private Sub and end with End Sub) and is generated automatically (see in the below section) with a specific name, you can call a Sub Procedure or write your own code within the Event code.

One common use of Workbook_Open Event is that people make application in Excel User Form and they want the Form look like a non-Excel, real Windows application. When user opens the Workbook, a Form pops up and the Excel application (the Excel background) is hidden.

You may ask why people do this instead of doing a real Visual Basic Application. The reason is that using VB.Net application very likely requires installation of .NET Framework but that would require Administration privilege, which could be a problem if you are not an IT administrator at workplace.

To me, I use Workbook_Open Event to apply formatting after I export data from Access to Excel. I cannot pre-format Excel because somehow Access would screw up the pre-formatting.

Example of  Excel Workbook_Open Event

1) Press ALT+11 to enter VBE (Visual Basic Editor)

2) Double click on ThisWorkbook > select Workbook > Select Open

hotkey_03

3) Insert your code between Private Sub and End Sub. For example, the below code assigns hotkey Crtl+Shift+k to Macro1 when Workbook is Opened

Private Sub Workbook_Open()
    Application.OnKey "^+k", "Macro1"
End Sub

If you want to know more about OnKey Method, click here

Note that Workbook_Open Event can be skipped by holding SHIFT button, but you need to open that workbook from another workbook. Simply put, open workbook A, hold shift, open workbook B

Alternative for Excel Workbook_Open Event using Auto_Open

The below method uses Auto_Open, which is an old approach for auto run Macro before Workbook_Open Event was implemented.

1) ALT+11 to enter VBE (Visual Basic Editor)

2) Insert Module

3) Insert the below code

Sub Auto_Open()
End Sub

4) If you already have a Sub Procedure called Macro1, then type

Sub Auto_Open()
    Macro1
End Sub

If you want to auto run User Form called UserForm1, then type

Sub Auto_Open()
    UserForm1.Show
End Sub

Outbound References

https://msdn.microsoft.com/en-us/library/office/ff194819%28v=office.15%29.aspx

Workbook Open Event | Worksheet Change Event

Events are actions performed by users which trigger Excel VBA to execute code.

Workbook Open Event

Code added to the Workbook Open Event will be executed by Excel VBA when you open the workbook.

1. Open the Visual Basic Editor.

2. Double click on This Workbook in the Project Explorer.

3. Choose Workbook from the left drop-down list. Choose Open from the right drop-down list.

Workbook Open Event in Excel VBA

4. Add the following code line to the Workbook Open Event:

MsgBox «Good Morning»

5. Save, close and reopen the Excel file.

Result:

Workbook Open Event Result

Worksheet Change Event

Code added to the Worksheet Change Event will be executed by Excel VBA when you change a cell on a worksheet.

1. Open the Visual Basic Editor.

2. Double click on a sheet (for example Sheet1) in the Project Explorer.

3. Choose Worksheet from the left drop-down list. Choose Change from the right drop-down list.

Worksheet Change Event in Excel VBA

Add the following code lines to the Worksheet Change Event:

4. The Worksheet Change Event listens to all changes on Sheet1. We only want Excel VBA to do something if something changes in cell B2. To achieve this, add the following code lines:

If Target.Address = «$B$2» Then

End If

5. We only want Excel VBA to show a MsgBox if the user enters a value greater than 80. To achieve this, add the following code line between If and End If.

If Target.Value > 80 Then MsgBox «Goal Completed»

6. On Sheet1, enter a number greater than 80 into cell B2.

Enter a Number Greater Than 80

Result:

Workbook Change Event Result

In this Article

  • What are VBA events?
    • Types of Events
    • Dangers of Using Code in Events
    • Disable Events
      • Workbook Events Examples (not exhaustive)
      • Workbook Open Event
      • Workbook New Sheet Event
      • Workbook Before Save Event
      • Workbook Before Close Event
      • Worksheet Event Examples (not exhaustive)
      • Worksheet Change Event
      • Worksheet Before Double Click Event
      • Worksheet Activate Event
      • Active X Control Events (not exhaustive)
      • Command Button Click Event
      • Drop Down (Combo Box) Change Event
      • Tick Box (Check Box) Click Event
      • UserForm Events (not exhaustive)
      • UserForm Activate Event
      • Change Event
      • Click Event
      • Chart Events
      • Application Events
      • Application.OnTime
      • Application.OnKey

What are VBA events?

Events are happening all the time when a user opens an Excel workbook and starts doing various actions such as entering data into cells or moving between sheets

Within the Visual Basic Editor (ALT+F11), sub routines are already set up which can get fired off when the user does something e.g. entering data into a cell.  The sub routine does not provide any action code, merely a ‘Sub’ statement and an ‘End Sub’ statement with no code between them. They are effectively dormant so nothing happens until you enter some code.

Here is an example based on the ‘Change’ event in a worksheet:

PIC 01

As a VBA programmer, you can add in code to make certain things happen when the user takes a specific action.  This gives you the chance to control the user, and to prevent them taking actions that you do not want them to do and which might damage your workbook.  For example, you may want them to save off their own individual copy of the workbook under another name, so that they do not affect the original, which may be being used by a number of users.

If they close the workbook, then they will automatically be prompted to save their changes.  However, the workbook has a ‘BeforeClose’ event and you can enter code to prevent the workbook being closed and firing off a ‘Save’ event.  You can then add a button to the worksheet itself and put your own ‘Save’ routine onto it.  You can also disable the ‘Save’ routine using the ‘BeforeSave’ event

An understanding of how events work is absolutely essential to a VBA programmer.

Types of Events

Workbook Events – these events are fired off based on what the user does with the workbook itself. They include user actions such as opening the workbook, closing the workbook, saving the workbook, adding or deleting sheet

Worksheet Events – these events are fired off by a user taking actions on a specific worksheet.  Every worksheet within the workbook has an individual code module, which contains various events specifically for that worksheet (not for all the worksheets).  These include user actions such as changing the contents of a cell, double clicking on a cell, or right clicking on a cell.

Active X Control Events – Active X controls can be added to a worksheet using the ‘Insert’ icon on the ‘Developer’ tab in the Excel ribbon.  These are often button controls to enable the user to take various actions under control of your code, but they can also be objects such as drop downs.  Using Active X controls as opposed to Form controls on the worksheet gives a whole scope for programmability. Active X controls give you far more flexibility from a programming point of view over using form controls in a worksheet.

For example, you could have two drop down controls on your worksheet.  You want the available list in the second drop down to be based on what the user chose in the first drop down. Using the ‘Change’ event on the first drop down, you can create code to read what the user has selected and then update the second drop down.  You could also de-activate the second drop down until the user has made a selection in the first drop down

UserForm Events – You can insert and design a professional looking form to use as a pop-up.  All the controls that you place on your form are Active X controls and they have the same events as the Active X controls that you might place on a worksheet

Chart Events – These events are only related to a chart sheet and not to a chart appearing as part of a worksheet. These events include resizing the chart or selecting the chart.

Application Events – These use the Application object in VBA. Examples would allow code to be fired off when a certain key is pressed or when a certain time is reached.  You could program a situation where the workbook is left open 24/7 and it imports data from an external source overnight at a pre-determined time.

Dangers of Using Code in Events

When you write code to do something when the user takes a certain action, you need to bear in mind that your code could be triggering other events, which could put your code into a continuous loop.

For example, suppose that you use the ‘Change’ event on a worksheet so that when the user puts a value into a cell, a calculation based on that cell is placed into the cell immediately to the right of it.

The problem here is that the placing of the calculated value into the cell triggers another ‘Change’ event, which then in turn triggers yet another ‘Change’ event, and so on until your code has run out of columns to use, and throws up an error message.

You need to think carefully when writing the code for the event to ensure that other events will not be triggered inadvertently

Disable Events

You can use code to disable events to get around this problem.  What you will need to do is to incorporate code to disable events whilst your event code is running and then re-enable events at the end of the code.  Here is an example of how to do it:

Sub DisableEvents()
Application.EnableEvents = False
Application.EnableEvents = True
End Sub

Bear in mind that this disables all events right across the Excel application, so this would also affect other functions within Excel.  If you use this for any reason, make sure that events are switched back on afterwards.

Importance of Parameters in Events

Events usually have parameters which you can use to find out more about what the user is doing and the cell location that they are in.

For example, the Worksheet Change event looks like this:

Private Sub Worksheet_Change(ByVal Target As Range)

By using the range object, you can find out the cell row/column coordinates that the user is actually in.

Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox Target.Column
MsgBox Target.Row
End Sub

If you only want your code to work on a certain column or row number, then you add a condition that exits the subroutine if the column is not the required one.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column <> 2 Then Exit Sub
End Sub

This gets around the problem of your code triggering multiple events, since it will only work if the user has changed a cell in column 2 (column B)

Workbook Events Examples (not exhaustive)

The workbook events are found under the ‘ThisWorkbook’ object in the VBE Project Explorer.  You will need to select ‘Workbook’ on the first drop down on the code window and then the second drop down will show you all the events available

Pic 02

Workbook Open Event

This event is fired off whenever the workbook is opened by a user.  You could use it to put a welcome message to a user by capturing their username

Private Sub Workbook_Open()
MsgBox "Welcome " & Application.UserName
End Sub

You could also check their username against a list held on a hidden sheet to see if they are authorised to access the workbook.  If they are not an authorised user, then you can display a message and close the workbook so that they cannot use it.

Workbook New Sheet Event

This event is triggered when a user adds a new sheet to the workbook

You could use this code to only allow yourself to add a new sheet, rather than have different users all adding sheets and making a mess of the workbook

Private Sub Workbook_NewSheet(ByVal Sh As Object)
Application.DisplayAlerts = False
If Application.UserName <> "Richard" Then
        Sh.Delete
End If
Application.DisplayAlerts = True
End Sub

Note that you need to switch off the alerts as a user warning will appear when the sheet is deleted which allows the user to circumvent your code.  Make sure that you turn the alerts back on afterwards!

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Workbook Before Save Event

This event is triggered when the user clicks on the ‘Save’ icon, but before the ‘Save’ actually takes place

As described earlier, you may want to prevent users saving their changes to the original workbook, and force them to create a new version using a button on the worksheet.  All that you need to do is to change the ‘Cancel’ parameter to True, and the workbook can never be saved by the conventional method.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Cancel = True
End Sub

Workbook Before Close Event

You can use this event to prevent users closing down the workbook, and again force them to exit through a worksheet button. Again, you set the ‘Cancel’ parameter to ‘True’.  The red X in the top right-hand corner of the Excel window no longer works any more.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = True
End Sub

Worksheet Event Examples (not exhaustive)

The worksheet events are found under the specific sheet name object in the VBE Project Explorer.  You will need to select ‘Worksheet’ on the first drop down on the code window and then the second drop down will show you all the events available

PIC 03

VBA Programming | Code Generator does work for you!

Worksheet Change Event

This event is triggered when a user makes a change to a worksheet, such as entering a new value into a cell

You can use this event to put an additional value or comment in next to the changed cell, but as discussed earlier, you do not want to start setting off a loop of events.

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column <> 2 Then Exit Sub
ActiveSheet.Cells(Target.Row, Target.Column + 1). Value = _
ActiveSheet.Cells(Target.Row, Target.Column). Value * 1.1
End Sub

In this example, the code will only work if the value is entered into Column B (column 2).  If this is true then it will add 10% to the number and place it into the next available cell

Worksheet Before Double Click Event

This event will fire off code if a user double clicks on a cell.  This can be extremely useful for financial reports such as a balance sheet or profit & loss account where numbers are likely to be challenged by managers, especially if the bottom line is negative!

You can use this to provide a drill-down facility, so that when the manager challenges a particular number, all they have to do is double click on the number, and the breakdown appears as part of the report.

This is very impressive from a user’s point of view, and saves them constantly asking ‘why is this number so high?’

You would need to write code to find out the heading / criteria for the number (using the Target object properties) and then filter the tabular data and then copy it into the report.

Worksheet Activate Event

This event occurs when the user moves from one sheet to another.  It applies to the new sheet that the user is moving to.

It could be used to ensure that the new sheet is completely calculated before the user starts doing anything on it.  It can also be used to only re-calculate that particular sheet without re-calculating the entire workbook.  If the workbook is large and has complicated formula in it, then re-calculating one sheet saves a lot of time

Private Sub Worksheet_Activate()
ActiveSheet.Calculate
End Sub

Active X Control Events (not exhaustive)

As discussed earlier, you can add Active X controls directly onto a worksheet.  These can be command buttons, drop downs, and list boxes

The Active X events are found under the specific sheet name object (where you added the control)  in the VBE Project Explorer.  You will need to select the name of the Active X control on the first drop down on the code window and then the second drop down will show you all the events available

PIC 04

Command Button Click Event

When you have put a command button onto a spreadsheet, you will want it to take some action.  You do this by putting code on the Click event.

You can easily put an ‘Are you sure message?’ on this so that a check is made before your code runs

Private Sub CommandButton1_Click ()
Dim ButtonRet As Variant
ButtonRet = MsgBox("Are you sure that you want to do this?", vbQuestion Or vbYesNo)
If ButtonRet = vbNo Then Exit Sub
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Drop Down (Combo Box) Change Event

An Active X drop down has a change event, so that if a user selects a particular item from the drop-down list, you can capture their choice using this event and then write code to adapt other parts of the sheet or workbook accordingly.

Private Sub ComboBox1_Change ()
MsgBox "You selected " & ComboBox1.Text
End Sub

Tick Box (Check Box) Click Event

You can add a tick or check box to a worksheet so as to provide option choices for the user.  You can use the click event on it to see if the user has changed anything on this.  The values returned are True or False according to whether it has been ticked or not.

Private Sub CheckBox1_Click ()
MsgBox CheckBox1.Value
End Sub

UserForm Events (not exhaustive)

Excel provides the ability for you to design your own forms.  These can be very useful to use as pop-ups to collect information or to provide multiple choices to the user.  They use Active X controls as described previously and have exactly the same events, although the events depend very much on the type of control.

Here is an example of a simple form:

PIC 05

When it is displayed this is what it looks like on screen

PIC 06

You would use events on the form to do things like enter a default company name when the form is opened, to check the company name input agrees to one already in the spreadsheet and has not been mis-spelt, and to add code to the click events on the ‘OK’ and ‘Cancel’ buttons

The code and events behind the form can be viewed by double clicking anywhere on the form

The first drop down gives access to all the controls on the form. The second drop down will give access to the events

PIC 07

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

UserForm Activate Event

This event is triggered when the form is activated, normally when it is displayed.  This event can be used to set up default values e.g. a default company name in the company name text box

Private Sub UserForm_Activate()
TextBox1.Text = "My Company Name"
End Sub

Change Event

Most of the controls on the form have a change event, but in this example, the company name text box can use the event to put a restriction on the length of the company name being entered

Private Sub TextBox1_Change ()
If Len (TextBox1.Text) > 20 Then
    MsgBox "The name is restricted to 20 characters", vbCritical
    TextBox1.Text = ""
 End If
End Sub

Click Event

You can use this event to take action from the user clicking on controls on the form, or even the form itself

On this form there is an ‘OK’ button, and having collected a company name, we would want to place it in a cell on the spreadsheet for future reference

Private Sub CommandButton1_Click ()
ActiveSheet.Range("A1"). Value = TextBox1.Text
Me.Hide
End Sub

This code acts when the user clicks the ‘OK’ button.  It puts the value in the company name input box into cell A1 on the active sheet and then hides the form so that user control is returned back to the worksheet.

Chart Events

Chart events only work on charts that are on a separate chart sheet, and not on a chart that is incorporated into a standard worksheet

Chart events are somewhat limited and cannot be used on a worksheet where you might well have multiple charts.  Also, users do not necessarily want to switch from a worksheet containing numbers to a chart sheet – there is no immediate visual impact here

The most useful event would be to find out the component of a chart that a user has clicked on e.g. a segment in a pie chart, or a bar in a bar chart, but this is not an event available on the standard range of events.

This problem can be solved by using a class module to add a ‘Mouse Down’ event which will return details of the chart component that the user has clicked on. This is used on a chart within a worksheet.

This involves some very complicated coding, but the results are spectacular.  You can create drill downs e.g. the user clicks on a pie chart segment and instantly that chart is hidden and a second chart appears in its place showing a pie chart of detail for the original segment, or you could produce the tabular data supporting that segment of the pie chart.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Application Events

You can use the Application object in VBA to fire off code according to a particular event

Application.OnTime

This can enable you to fire off a piece of code at regular intervals for as long as the workbook is loaded into Excel.  You may want to auto-save your workbook to a different folder every 10 minutes, or leave the worksheet running overnight so as to bring in the latest data from an external source.

In this example, a sub routine is entered into a module.  It displays a message box to every 5 minutes, although this could easily be another coded procedure.  At the same time, it resets the timer to the current time plus 5 more minutes.

Every time it runs, the timer resets to run the same sub routine in another 5 minutes time.

Sub TestOnTime()
MsgBox "Testing OnTime"
Application.OnTime (Now () + TimeValue("00:05:00")), "TestOnTime"
End Sub

Application.OnKey

This function enables you to design your own hot keys.  You can make any key combination call a sub routine of your creation.

In this example the letter ‘a’ is redirected so that instead of placing an ‘a’ in a cell, it will display a message box.  This code needs to be placed in an inserted module.

Sub TestKeyPress()
Application.OnKey "a", "TestKeyPress"
End Sub
Sub TestKeyPress()
MsgBox "You pressed 'a'"
End Sub

You run the sub routine ‘TestKeyPress’ first of all.  You only need to run this once. It tells Excel that every time the letter ‘a’ is pressed it will call the sub routine ‘TestKeyPress’.  The sub routine ‘TestKeyPress’ just displays a message box to tell you that you pressed key ‘a’.  It could of course load a form or do all sorts of other things.

You can use any key combination that you can use with the ‘SendKeys’ function

To cancel this functionality, you run the ‘OnKey’ statement without the ‘Procedure’ parameter.

Sub CancelOnKey()
Application.OnKey "a"
End Sub

Everything is now back to normal.

Here are some commonly used workbook events.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Event Discription
ActivateEvent Occurs when the workbook is activated.
BeforeClose Occurs before the workbook closes. If the workbook has been changed, this event occurs before the user is asked to save changes.
BeforePrint Occurs before the workbook (or anything in it) is printed.
BeforeSave Occurs before the workbook is saved.
Deactivate Occurs when the workbook is deactivated.
New Occurs when a new workbook is created.
NewChart Occurs when a new chart is created in the workbook.
NewSheet Occurs when a new sheet is created in the workbook.
Open Occurs when the workbook is opened.
SheetActivate Occurs when any sheet is activated.
SheetChange Occurs when cells in any worksheet are changed by the user or by an external link.
SheetDeactivate Occurs when any sheet is deactivated.
SheetSelectionChange Occurs when the selection changes on any worksheet. Does not occur if the selection is on a chart sheet.
WindowActivate Occurs when any workbook window is activated.
WindowDeactivate Occurs when any workbook window is deactivated.
WindowResize Occurs when any workbook window is resized.

Code for workbook events are saved in the ThisWorkbook module.

At the top of the code window change General to Workbook in the first drop down menu.

From the second drop down menu at the top of the code window, select which event you want to write a procedure for.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Example Workbook Event Procedures

The examples below are intended to illustrate the workings of each event rather than to provide commercially useful procedures.

Workbook Open Event

This procedure shows a welcome message in the status bar and window caption.  It also presents the user with a welcome message on opening the workbook.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Private Sub Workbook_Open()
Dim UserName As String
UserName = Application.UserName

'Display welcome message on open
MsgBox "Hi There " & UserName & ", the time and date is is " & Now

' Display message in status bar and window caption
Select Case Time
    Case Is < 0.5
        With Application
            .StatusBar = "Good Morning " & UserName _
            & ". You opened this file at " & Time
            .Caption = "Good Morning " & UserName _
            & ". You opened this file at " & Time
        End With
    Case 0.5 To 0.75
        With Application
            .StatusBar = "Good Afternoon " & UserName _
            & ". You opened this file at " & Time
            .Caption = "Good Afternoon " & UserName _
            & ". You opened this file at " & Time
        End With
    Case Is > 0.75
        With Application
            .StatusBar = "Good Evening " & UserName _
            & ". You opened this file at " & Time
            .Caption = "Good Evening " & UserName _
            & ". You opened this file at " & Time
        End With
End Select

'If weekday is Monday display XYZ report reminder
If Weekday(Date) = vbMonday Then _
MsgBox "It's Monday again, you need to file the XYZ Report"
End Sub 

New Sheet Event

The New Sheet event creates an argument called Sh. Sh represents the worksheet that has been created.  In the example code below we use Sh to name the new sheet.

Sh.Name = SheetName

This example procedure  asks the user to name the sheet when it is created.  The user input is stored in a variable called SheetName.  The date and time the sheet is created is displayed in cell A1.

Private Sub Workbook_NewSheet(ByVal Sh As Object)
Dim SheetName As String
Dim UserName As String
UserName = Application.UserName
SheetName = _
InputBox("You are adding a new sheet.  What would you like to call it?")
Sh.Name = SheetName
Range("A1") = "Sheet Created by " & UserName & " on " & Now
End Sub

Sheet Activate Event

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

The Sheet Activate event also creates an argument called Sh which represents this worksheet that has just been activated.  This procedure displays a welcome message when any sheet is activated.

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox "Welcome to worksheet: " & Sh.Name
End Sub

After Save Event

This procedure displays a message confirming the file name and path of the workbook after it has been saved.

Private Sub Workbook_AfterSave(ByVal Success As Boolean)
Dim ThisWorkBookName As String
Dim ThisWorkBookLocation As String
ThisWorkBookName = ActiveWorkbook.Name
ThisWorkBookLocation = ActiveWorkbook.Path
MsgBox "You just saved " & ThisWorkBookName & " to " & ThisWorkBookLocation
End Sub

Before Close Event

The Before Close event creates a Cancel argument which if set to True will prevent the file being closed.  In this example the procedure will only let the user close the file if it is home time.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Time < "18:00" Then
MsgBox "It's not time to go home yet. Carry on working."
Cancel = True
End If
End Sub

Before Print Event

The Before Print event has an argument called Cancel which can used to cancel the print.  The procedure below requires the user to enter a password before printing.  They get three attempts: everytime they get the password wrong the Cancel argument is set to True.

The procedure also hides column B and C before printing and then calls a separate procedure to unide them (the UnhideColumnsAfterPrint procedure would be stored in a normal module).

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Private Sub Workbook_BeforePrint(Cancel As Boolean)
Dim Password As String
Dim x As Integer
'Ask for password before printing (3 attempts)
For x = 1 To 3
    Password = InputBox("Please enter password to print")
    If Password <> "1234" Then
        Cancel = True
        MsgBox "Sorry that password is not recognised. You have " _
        & 3 - x & " attempts remaining"
        Else: Exit For
    End If
Next x

'Hide columns B and C before printing
Worksheets("Printing With Hidden Columns").Range("B:C")._
EntireColumn.Hidden = True

'Run the UnhideColumnsAfterPrint procedure one second after the event
Application.OnTime EarliestTime:=Now + TimeValue("0:00:01"), Procedure:="UnhideColumnsAfterPrint"
End Sub

Window Resize Event

The Window Resize event has an argument called Wn which represents the workbook’s window.  The example procedure maximises the window whenever the user resizes it.

Private Sub Workbook_WindowResize(ByVal Wn As Window)
Wn.Caption = "STOP TRYING TO RESIZE ME!!!!!"
Wn.WindowState = xlMaximized
End Sub

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Worksheet Events

Here are some commonly used worksheet events.

Event Description
ActivateEvent Occurs when the worksheet is activated.
BeforeDoubleClick Occurs when the worksheet is double-clicked, before the default double-click action.
BeforeRightClick Occurs when the worksheet is right-clicked, before the default right-click action.
Calculate Occurs after the worksheet is recalculated.
Change Occurs when something changes in the Worksheet cells.
Deactivate Occurs when the worksheet loses focus.
FollowHyperlink Occurs when you click any hyperlink on a worksheet.
PivotTableUpdate Occurs after a PivotTable report is updated on a worksheet.
SelectionChange Occurs when the selection changes on a worksheet.

Worksheet events are placed in the relevant worksheet module.

At the top of the code window change General to Worksheet in the first drop down menu.

From the second drop down menu at the top of the code window, select which event you want to write a procedure for.

Worksheet Change Event Examples

Automatically Save Workbook if Cell’s Value Change

This procedure automatically saves the workbook if any cell in the specified range changes.  The If’s condition uses the Intersect method. Intersect, as it name suggests returns the intersecting range of cells that result when two or more ranges overlap.  If no cells overlap intersect will return nothing.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Intersect(FirstRange, SecondRange etc)

The procedure is automatically run with the Worksheet Change event. Target is the range that has been changed. The Target range is automatically returned by the Worksheet Change event.

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("A1:D10")) Is Nothing Then
    Exit Sub
Else: ThisWorkbook.Save
End If

End Sub

This version will save the workbook if any cell is changed.

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, ActiveSheet.UsedRange) Is Nothing Then
    Exit Sub
Else: ThisWorkbook.Save
End If

End Sub

Automatically Add Comments When Cell’s Value Changes

In this example the Worksheet change event triggers a procedure that automatically adds a comment to a cell.  The comment includes the date and time of the cell entry, the value entered in the cell and the username of the person who added the enty.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim MyCell As Range
Dim Username As String
Username = Application.Username

'If cell's content is deleted, clear comments
For Each MyCell In Target
    If MyCell.Value = "" Then
        Target.ClearComments
        Exit Sub
    End If
Next MyCell

For Each MyCell In Target

'If cell doesn't have any comments add comment...
If MyCell.Comment Is Nothing Then
    '...displaying current data and time, cell's value and username
    MyCell.AddComment Now & " - " & MyCell.Value & " - " & Username

'If cell already has comment add new text to existing comment, _
do not overwrite.
Else
   MyCell.Comment.Text _
   Text:=vbNewLine & Now & " - " & MyCell.Value & " - " & Username, _
   Start:=Len(Target.Comment.Text) + 1, _
   Overwrite:=False
End If

'Autosize comments
MyCell.Comment.Shape.TextFrame.AutoSize = True

Next MyCell

End Sub

Validate Data on Entry

In this example the Worksheet Change event checks to see that user has entered a numeric value in the range SalesCells.  If the value is not numeric a warning message is displayed and the value is deleted.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rg As Range
Dim SalesCells As Range
Set SalesCells = Range("B4:G13")

'If the cell change is outside the SalesCells range exit procedure
If Intersect(Target, SalesCells) Is Nothing Then Exit Sub
   
For Each rg In Intersect(Target, SalesCells)
'If cell entry is not numeric delete entry and show message
    If Not IsNumeric(rg) Then
        MsgBox "You must enter a numeric value in this cell"
        Target.ClearContents
        Target.Activate
    End If
Next rg

End Sub

Selection Change Event

In this example, the active cell’s column and row are formatted with a grey background.  The formatting occurs on selection change.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Cells
    .Interior.Color = xlNone
    .Font.Color = vbBlack
End With
With ActiveCell
    With .EntireColumn
        .Interior.Color = rgbDarkGrey
        .Font.Color = vbWhite
    End With
    With .EntireRow
        .Interior.Color = rgbDarkGrey
        .Font.Color = vbWhite
    End With
End With
End Sub

Before Delete Event

This procedure prevents deletion of a sheet by temporarily protecting the workbook.

Private Sub Worksheet_BeforeDelete()
ThisWorkbook.Protect
Application.OnTime EarliestTime:=Now, Procedure:="UnProtectBook"
End Sub

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

OnKey Events

Use the OnKey method to assign shortcut keys to your macros.

Application.OnKey(Key, Procedure)

OnKey Parameters

Name Required/Optional Data Type Description
Key Required String A string indicating the key to be pressed.
Procedure Optional Variant The name of the procedure to be run. If Procedure is «» (empty text), nothing happens when Key is pressed. If Procedure is omitted, Key reverts to its normal result in Microsoft Excel.

Refer to specific keys using the codes shown below.

Key Code
BACKSPACE {BACKSPACE} or {BS}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
CLEAR {CLEAR}
DELETE or DEL {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER (numeric keypad) {ENTER}
ENTER ~ (tilde)
ESC {ESCAPE} or {ESC}
HELP {HELP}
HOME {HOME}
INS {INSERT}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
RETURN {RETURN}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 through F15 {F1} through {F15}
Combine with Precede the key code by
SHIFT + (plus sign)
CTRL ^ (caret)
ALT % (percent sign)

Assign a Custom Keystroke

To assign the shortcut keys automatically when the workbook opens, place the OnKey statements in the ThisWorkbook module in the Workbook Open event procedure.

Private Sub Workbook_Open()
'Setup OnKeys
Application.OnKey "+{F1}", "SHIFTF1"
End Sub

The procedure the shortcut key calls can be placed in a normal module.

Sub SHIFTF1()
Dim User As String
User = Application.Username
ActiveCell = "Created by " & User & " on " & Now
End Sub

Please note that the OnKey assignment applies to all open workbooks.

Unassign a Custom Keystroke

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

To unassign a custom keystoke, omit the Procedure parameter in the OnKey statement.  Place this code in the ThisWorkbook module using the Before Close event procedure.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
'UnAssign OnKeys
Application.OnKey "+{F1}"
End Sub

Disable Built In Excel Keystokes

If you want to disable built in keystokes return an empty text string in the Procedure argument. The following OnKey statement disables ALT F4 which would normally close Excel.

Application.OnKey "%{F4}", ""

Like this post? Please share to your friends:
  • Vba excel workbook методы
  • Vba excel union примеры
  • Vba excel автоподбор высоты строк
  • Vba excel union range
  • Vba excel workbook protect