Read our blogs, tips and tutorials
Try our exercises or test your skills
Watch our tutorial videos or shorts
Take a self-paced course
Read our recent newsletters
License our courseware
Book expert consultancy
Buy our publications
Get help in using our site
545 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owl trainers only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Written by Andy Brown
In this tutorial
When asked for what could blow his programme off course, Harold Macmillan famously said: "Events, dear boy, events" (or did he?). Much the same can be said of your program in Excel VBA. Whenever you open, save or close a workbook, print something out, click on a cell, type something in or right-click or double-click, events happen - and to each and every one of these events you can react with judiciously written code.
Suppose that you want to make sure that when someone using your workbook opens it, a macro automatically takes them to the correct worksheet. You could do this with the following event-handling macro:
Private Sub Workbook_Open()
'go to the correct worksheet on opening
Worksheets("ImportantSheet").Select
End Sub
So: how do you write macros like this?
The first step is to decide whether your macro is going to handle an event to do with the entire workbook, or a single worksheet. Here are some examples:
Scope of event | Examples |
---|---|
Workbook | Opening, saving or closing a file, printing anything |
Worksheet | Clicking on a cell, changing a cell's value, right-clicking on a cell |
A fuller list of examples is given in later parts of this tutorial. For our example, we want to attach code to the workbook, so you need to double-click on ThisWorkbook:
Double-click on the workbook in the code window (or right-click on it and choose to view its code).
This is almost the only time in Excel VBA that you should write code in anything other than a module.
You can now choose to attach code to the workbook itself (there's actually no other choice, so it's annoying that this isn't selected automatically for you):
Click on the drop arrow where it says General, and choose Workbook.
You can now choose the particular event you want to handle by clicking on the right-hand drop arrow:
Choose from the list of possible events which can happen in a workbook's life.
Note that on this occasion there was actually no need to do this, as Excel guessed that it was the workbook's Open event that you wanted to intercept and "handle".
You can now type in any code that you want to run when a user opens your workbook! When you save your file and re-open it, then all things being well your code will run.
Whenever an event begins with the word Before it means that you can either react to the event which is about to occur and - if desired - prevent it happening. Here's an example which stops anyone closing workbooks if they haven't filled in a version control number.
Option Explicit
'holds the current version number
Private VersionNumber As Integer
Private Sub Workbook_Open()
'read in the version number in cell A1
Worksheets(1).Select
VersionNumber = Range("A1").Value
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim NewVersionNumber As Integer
'if version number hasn't changed, can't close
Worksheets(1).Select
NewVersionNumber = Range("A1").Value
If VersionNumber = NewVersionNumber Then
'user hasn't changed version number - abort
MsgBox "Must update version number first"
Cancel = True
End If
End Sub
Here's what this macro does:
Whenever anyone opens the workbook, the code attached to the Open event reads the value of cell A1 on the first sheet into a private variable called VersionNumber.
When someone then tries to save the workbook, code attached to the BeforeSave event checks to see if the user has updated this version number, and if not displays a message and cancels the event.
In the above code, the line:
'cancel this event
Cancel = True
will cancel whichever event it was which triggered the macro (in this case, saving the workbook).
It's worth mentioning that if anyone holds down the SHIFT key at the point at which they open a workbook containing your macros it will disable them. Just to warn you!
You can learn more about this topic on the following Wise Owl courses:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2024. All Rights Reserved.