Excel All Versions - Level 7 Course Book Revised PDF
Excel All Versions - Level 7 Course Book Revised PDF
Excel All Versions - Level 7 Course Book Revised PDF
In both cases, the selection is tested and if true, a message is displayed to explain the
problem before terminating execution of the procedure.
In the following example, an input box is displayed for the user to enter a number. If
the user accidentally enters a text value or clicks Cancel (both string values), a run-time
error occurs when the procedure attempts to use the string in the calculation.
By using an If... Then... Else function, together with the IsNumeric function to check
that the input is valid before attempting the calculation, the run time error can be
handled in a more user-friendly way, eg:
There are several Is... functions in VBA that can be used in a similar way:
IsArray
IsDate
IsEmpty
IsError
IsMissing
IsNull
IsObject
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook (VBA
project) that you want to add code to.
3. Open the module sheet containing the code or, insert a new
module.
4. Position the cursor in the procedure where you want to add
the error handling code.
5. Type If.
6. Enter a valid test to validate a condition encountered by the
procedure at that point.
7. Type Then.
8. Press Enter.
9. Type code to execute if the test is true.
10. Press Enter.
11. Type Else.
12. Press Enter.
13. Type code to execute if the test is false.
14. Press Enter
15. Type End If.
ERROR TRAPPING
Discussion
While If...Then...Else is a good, simple way of testing for correct input, it is not able to
handle all errors under all circumstances. In most cases, error trapping code will almost
certainly be needed. This comes in three forms:
On Error Resume Next
On Error GoTo
Resume
The error “trap” is “turned on” and “sits in wait” until an error occurs or until the
“trap” is “turned off”. The On Error statement is normally written into the procedure
just above where the anticipated error may occur. In many cases, this will be at the top
of the procedure just below any variable and/or constant declarations.
By writing the code as follows, the run-time error window will be ignored and the
procedure will successfully continue and hide all the toolbars.
The following example deletes ALL files from three folders (Data1, Data2 and Data3)
on the H:\ drive.
Kill "h:\Data1\*.*"
Kill "h:\Data2\*.*"
Kill "h:\Data3\*.*"
If a folder does not contain any files, the following run-time error message will occur:
This is a classic case of where the error can be ignored; if the folder is already empty,
then it does not need emptying, so VBA can safely ignore it and continue with the next
one.
Kill "h:\Data1\*.*"
Kill "h:\Data2\*.*"
Kill "h:\Data3\*.*"
In the earlier example on page 6 where the user is prompted for a numeric input, On
Error Resume Next would negate the need for the If... Then... Else.
The result in this case, however, is hardly ideal because although the run-time error
message does not appear, the procedure results in nothing happening! This is where a
different On Error statement is needed.
errhandle:
MsgBox "Invalid Data entered or user clicked Cancel"
End Sub
It is true that this code in its current form does not contribute any more than using the
If...Then...Else explained on page 7. Its advantage, however, lies in its ability to return
to where the error occurred and attempt the statement again. This involves the use of
the word Resume.
Resume
The keyword Resume tells VBA to retry the statement that failed. It can only be used as
part of an error handling routine, and is always used on its own (eg. On Error Resume
will cause an error). The error handling routine above, therefore, could explain the
problem the return the user to try again as follows:
errhandle:
MsgBox "Invalid Data entered or user clicked Cancel"
Resume
End Sub
The code above, however, does not give the user an opportunity NOT to return and try
again. So the next step in making the error handling routine as user-friendly as
possible, is to provide an interactive message box displaying a message explaining the
problem, asking whether the user WANTS to try again, and providing two buttons
(Yes and No) with which to respond.
Creating an interactive message box is covered in the Excel Introduction to VBA
Course. An extract of the course materials are given in Appendix IV on page 96. The
example below assumes knowledge and experience of this topic.
errhandle:
response = MsgBox("Invalid Data Entered. Do you want to try again?", vbYesNo)
If response = vbYes Then Resume
The final (and very important!) step is to prevent the error handling routine being
executed when the procedure runs WITHOUT any errors. This is achieved by including
the words Exit Sub immediately above the error routine label. The complete procedure
with error handling code is given below:
Sub CalculateInterest
Exit Sub
errhandle:
response = MsgBox("Invalid Data Entered. Do you want to try again?", vbYesNo)
If response = vbYes Then
Resume
End If
End Sub
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook (VBA
project) that you want to add code to.
3. Open the module sheet containing the code or, insert a new
module.
4. Position the cursor on the line below the Sub statement.
5. Type On Error GoTo errhandle (or other “label” to identify a
point further down in the procedure where the procedure
must divert to if a runtime error occurs.
6. A the bottom of the procedure and immediately above the End
Sub statement, type errhandle (or other label used).
7. Type a colon.
8. Press Enter.
9. Type appropriate error handling code for the anticipated error
using the examples above.
10. Position the cursor on the line immediately above the
errhandle label.
11. Type Exit Sub.
12. Press Enter.
Sub CalculateInterest
Exit Sub
errhandle:
response = MsgBox("Invalid Data Entered. Do you want to try again?",
vbYesNo)
If response = vbYes Then
Resume
End If
End Sub
The solution is to substitute the following code as the error handling routine:
errhandle:
If Err.Number = 13 Then
response = MsgBox("Invalid Data Entered. Do you want to try again?", vbYesNo)
End If
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook (VBA
project) that you want to add code to.
3. Open the module sheet containing the code or, insert a new
module.
4. Position the cursor on the line below the Sub statement.
On Error GoTo 0
This statement disables a previous On Error Resume Next or On Error Goto Label
statement. When the next error occurs, an error message will be generated and the
procedure will fail, eg:
Kill "h:\Data1\*.*"
Kill "h:\Data2\*.*"
Kill "h:\Data3\*.*"
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook (VBA
project) that you want to add code to.
3. Open the module sheet containing the code or, insert a new
module.
4. Position the cursor in the procedure where you want the error
handling no longer to have an effect.
5. Type On Error GoTo 0.
6. Press Enter.
Err.Description
A common way of creating a user-friendly run time error message is by creating a
custom message box quoting the error number and the error description. For example,
the code could be as follows (line continuation characters have been used for clarity but
are not required):
It is true to say that this message box does not say much more than the normal, run-
time error window, but it is rather less scary and upon clicking OK, does not
potentially leave the procedure hanging in break mode.
EXERCISE
DEALING WITH POTENTIAL ERRORS IN PROCEDURES
10. Leave this file open and switch back to the Trap Error workbook.
11. Run the Delete Old File macro and attempt to delete Remove Me Too. Is your
previous code handling the error correctly?
12. De-activate the error handling code by commenting out the On Error GoTo
statement at the top of your procedure.
13. Run the Delete Old File macro again.
14. Note the error message. How does it differ from the one displayed in 4 above?
(Tip: note the error number)
15. Edit the DeleteOldFile sub procedure with some additional error-trapping code
to deal with both potential errors in a more user-friendly way.
16. Re-activate the error handling code at the top of the procedure.
17. Test the macro by attempting again to delete Remove Me Too.
18. The file should be successfully deleted.
19. Save and close all open files.
Application.Dialogs(xlDialogSaveAs).Show
Procedures
1. Launch or switch to the VB Editor.
2. Identify in the Project Explorer pane, the workbook (VBA
project) that you want to add code to.
3. Open the module sheet containing the code or, insert a new
module.
4. Position the cursor in the procedure where you want to show
the built-in dialog box.
5. Type Application.
6. Type a full stop.
7. Type Dialogs.
8. Type an opening bracket (.
9. Type or select from the list the dialog box required.
10. Type a closing bracket ).
11. Press Enter.
USER-DEFINED FORMS
Discussion
As with built-in dialog boxes, User-Defined Forms (or just User Forms) can be created
to allow an applications to interact with the user. UserForms are, in essence, dialog
boxes that you design yourself for a special purpose that is not met by the built-in ones.
Procedures
1. Launch the VB Editor.
2. Right-click the workbook that you want to insert the
UserForm into.
3. Point to Insert .
4. Select UserForm.
It is advisable to have clear in your mind what controls the form should contain before
you start. Design the form on paper before you start.
Procedures
1. Click in the Toolbox, the button for the control that you want
to draw on the form.
2. Click the mouse pointer (black cross) on the form where you
want the top left corner of the control to be placed.
3. Point to the grey border on the edge of the control (mouse
Procedures
1. Click the first control that you want to include in the group.
2. Hold down the SHIFT key.
3. Click the next control that you want to include in the group.
4. Continue holding down the SHIFT key and clicking control to
include in the group.
5. Release the SHIFT key when all the controls have been
selected.
6. Move or resize any of the grouped control.
7. Click the Format menu.
8. Point to the appropriate command to format and layout the
grouped controls.
CONTROL PROPERTIES
Each form control has a list of properties that can be displayed and (if necessary)
changed in the Properties pane.
Many properties can be modified by directly formatting the control on the form; others
are set from the properties window. Properties can also be set or modified at run-time,
ie. when the form is displayed.
A comprehensive list of all properties for all form control would be too long and
unnecessary for this booklet, but help can be sought by clicking onto a property in the
properties pane and pressing F1.
For the purposes of a UserForm, the property that would usually need to be set for all
controls on the form is the Name property. Giving the controls a clear, consistent and
descriptive name makes them easier to identify when it comes to programming the
form.
PROGRAMMING A USERFORM
Discussion
UserForms and controls have a predefined set of events. For example a command
button has a “click” event, a procedure that runs when the user clicks the command
button. UserForms have an “initialise” event that runs when the form is loaded.
In order for a UserForm to work in the expected way (ie. as a dialog box), it has to have
at least two event procedure – one for when the OK button is pressed and a second for
when the Cancel button is pressed.
To write a control or form event procedure, open a module by double clicking the form
or control. A default event will appear on the module sheet but this can be changed by
selecting a different one from the procedure drop-down list at the top right of the
window.
Event procedures include the name of the control. For example, the name of the click
event procedure for a command button named cmdOK is
Private Sub cmdOK_Click. “Private” because the sub procedure should not show in
the Macro list in Excel, it does not need to because it is purely for use by the OK button
on the form.
Procedures
1. Double click the Cancel button on the form design.
2. Add code as necessary (see examples below).
3. Double-click the form in the Project Explorer pane.
4. Double-click the OK button on the form design.
5. Add code as necessary (see examples below).
6. Double click the form in the Project Explorer pane.
All the possible ways of programming a form and its controls’ events are too numerous
and varied to mention in any document. The examples given below, therefore, apply to
the more commonly used controls and are given as a guide only. Additional examples
and help can be obtained from the VB Editor help, and on various websites including
the Microsoft Developer Network at:
http://msdn.microsoft.com/en-us/library/aa220733(office.11).aspx
Unload frmDataEntry
frmDataEntry.txtName.Value
frmDataEntry.txtName.Value
you can use...
Me.frmDataEntry.txtName.Value
Text Boxes
Typically, when the OK button is clicked, text entered into a text box will need to be
transferred to a cell on a sheet, eg:
ActiveSheet.Range(“A2”).Value = frmDataEntry.txtName.Value
“Value” can be omitted because VBA always defaults to the value property for a range
object if the method or property is omitted. In addition, if the form must write the text
into cell A1 of the sheet that the form is being run from, there is no need to include
ActiveSheet. Hence, the code can be abbreviated to:
Range(“A2”) = Me.txtName
Range(“A3”) = Me.cmbDepartment
or
Range(“A4”) = Me.lstLocation
Under other circumstances, it may be that the combo box or list box is designed to give
the user options to choose from. In the following example, a list box has been used to
give the user a choice of files to open. The code, therefore, would be:
The above code assumes that the file to open is in the active, default folder. It may be
safer, therefore, to concatenate the correct path to the value returned by the control, eg:
In the following example, a combo box has been placed on the form to give the user a
selection of fonts to use. Assuming that the range to format is A1 to E1, the code would
be as follows:
Range(“A1:E1”).Font.Name = Me.cmbFontName
Option Buttons
Although not necessary if only one set of option buttons are used on a form, it is good
practice to draw them inside a frame. Only one option button can be selected at a time
so when one button is “pressed in,” another is “pushed out” (hence, radio buttons).
Invariably, a decision will need to be made which option button is selected and thus, an
If structure used to carry out the necessary actions.
In the following example, a frame has been set up on a form with two option buttons,
one for selecting male and one for selecting female. Whichever of the two is chosen
must be placed into cell B4 as M or F.
Check Boxes
Because a check box has two conditions – true or false, an If statement has to be used to
evaluate them. In the following example, a check box has been used for the user to state
whether to print the workbook or not.
The picture below, a spin button and a text box have been placed on a UserForm side
by side.
The code for making the value of the spin button visible in the text box would be added
to the spin button’s On_Change event. As the value in the spin button changes, it is
transferred to and made visible in the text box.
Procedures
1. Double-click the spin button on the form design.
2. Add the following code to the button’s On_Change event
procedure.
a. Private Sub spnCopies_Change()
i. Me.<text box name> = Me.<spin box name>
b. End Sub
3. Double-click the form in the Project Explorer pane.
A spin button’s values (ie. how high and low they can
go) can be controlled by using its Max and Min
properties.
The above procedure is purely to make the value of the spin button visible to the user
while using the form. Additional code has to be added to the OK button’s on click event
to make use of the spin button’s value.
In the following example, a spin button has been created on a form to prompt the user
for how many copies to print. The code uses the spin button’s value to print the
requested number of copies.
ActiveSheet.PrintOut Copies:=Me.spnCopies
FORM EVENTS
The topic above deals with events associated with form controls. The form itself also
has “events” that can be assigned a procedure. As with control events, the number and
variety of examples is too great to cover in this booklet. A couple of commonly used
examples, however, are given below to demonstrate use of the Initialize event. The
initialize event occurs when the form loads (just before it becomes visible on the screen)
and is often used to set default values for its controls and for populating combo and list
boxes.
Example A populates a combo box with four cities and Example B applies default
values to a text box and check box.
Example A
With Me.cmbLocations
.AddItem “Belfast”
.AddItem “Cardiff”
.AddItem “Edinburgh”
.AddItem “London”
End With
End Sub
Example B
Me.txtLocation.Value = “London”
Me.chkPrint.Value = True
End Sub
DISPLAYING A USERFORM
To display a user form, use the Show method for the form in question. This would be
written on a normal module sheet in the same workbook that the form has been created
in. The following example displays the UserForm named frmDataEntry:
Sub DisplayForm()
frmDataEntry.Show
End Sub
Once the procedure has been written, a method of running it from Excel needs to be
chosen. This would be the same as for any other macro, ie. button, menu or keystroke.
The code could also be included as part of a larger procedure, or called into one as a
separate sub procedure.
Procedures
1. Launch the VB Editor.
2. Identify the workbook containing the form that you want to
show.
3. Insert a module sheet in the workbook.
4. Type the following code:
Sub ShowForm
<formname>.Show
End Sub
5. Run the userform
EXERCISE
CREATING A USERFORM
Task - To create a UserForm to prompt for Text, ComboBox and CheckBox information.
Label
Text
Command
Buttons
Label
Combo Box
Check
Boxes Image
4. Assign an "on-click event" (what will happen when the control is clicked) to the Cancel
buttons by double clicking it and typing the following code:
Unload frmDataEntry
5. Double-click the form in the Project Explorer to return to its design window.
6. Assign an “initialize event” to the form (what happens when the form starts up) by
double clicking the form background and typing the following code. This is necessary
to load (“populate”) the combo box:
With frmDataEntry.comColour
.AddItem "Red"
.AddItem "Blue"
.AddItem "Green"
End With
7. Return to the form design window.
8. Double-click the OK button and add the following code. This is necessary to
“implement” the userform:
Range("A1").Value = frmDataEntry.txtInput.Value
Select Case frmDataEntry.comColours
Case Is = "Red"
Range("A1").Font.Color = vbRed
Case Is = "Blue"
Range("A1").Font.Color = vbBlue
Case Is = "Green"
Range("A1").Font.Color = vbGreen
End Select
Unload frmDataEntry
9. Finally, write a short sub procedure on a new module sheet to show the form:
Sub EnterData()
frmDataEntry.Show
End Sub
10. Create a custom button on your toolbar to run the EnterData macro and check correct
data entry in cell A1. Correct any code, if necessary.
11. Save and close the file.
Excel 2000 – 2003 Forms toolbar Excel 2000 – 2003 Control Toolbox toolbar
In Excel 2007 both Form and ActiveX controls are available by clicking the Insert
button in the Controls group of the Developer tab on the Ribbon.
Form Controls
Form controls are only available to use on an Excel worksheet. Because these controls
don’t require any VBA code behind them to work (although a limited amount of code
can be added if required in Excel 2000 - 2003), they are fairly easy to create using
standard Excel methods and commands. This, however, means that they are not
especially flexible or powerful.
The most common form control is the command button; drawn on a worksheet and set
up so that when it is clicked, a macro runs.
Using form controls is covered on the Microsoft Excel Level 4 training course.
ACTIVEX CONTROLS
Discussion
ActiveX controls are available for use directly on an Excel worksheet OR they can be
used in the VB Editor to create user forms (see Lesson 2 -
Built-in Dialog Boxes and custom UserForms
on page 19).
ActiveX controls are more useful than the form controls because they can be
programmed more extensively by making them respond to “events.”
An event occurs when a user or the computer itself makes something “happens;” ie.
they initiate an action. The commonest way of creating an event is by clicking a button
on the screen or pressing a key on the keyboard. The computer itself can initiate an
event by using an internal timer or clock, eg. pop up a meeting reminder.
With ActiveX controls, as well as a simple click, other less common events (but ones
that can be “trapped” and programmed) are: double click; change (eg. a new item is
selected from a combo box or list box); user leaving the control and shifting focus to
another control; or back to the Excel interface, to name but a few.
ActiveX controls also have many “Properties” that can be used to change the
characteristics of a control (eg. size, font, colour). The properties of a control depend on
its type although some - such as Name - are common to all.
CONTROL PROPERTIES
Discussion
Each control has its own distinct set of characteristic or “properties.” Properties define
how the control looks and behaves.
Properties vary for different controls vary. For example, a Spin Button control has a
“Max” and a “Min” property that restricts the highest and the lowest value that it can
spin to. This property is irrelevant to, say, a Combo Box control in the same way as a
Combo Box’s “ListFillRange” property (the data to use for populating the combo box)
would be irrelevant to a Spin Button. As a result, properties that are not applicable to a
control are omitted from the properties list.
Some properties, however, are common to many controls. The list below gives the more
commonly used ones.
Property Description
AutoSize If True, the control resizes itself automatically based on the length of
text entered into it.
BackColor The background colour of a control.
BackStyle The style of the background (either transparent or opaque).
Procedures
1. Right click the control that you want to change the properties of.
2. Select Properties.
3. Edit or add property value as necessary.
MOVING A CONTROL
Discussion
By pointing at an ActiveX control, you can re-position elsewhere on the worksheet.
When you re-position a control from one location to another, its size stays the same
size.
Procedures
1. Click on the control that you want to reposition.
2. Drag the control to another part of the worksheet.
3. Release the mouse button
SIZING A CONTROL
Discussion
By pointing at a sizing handle and clicking and dragging, you to change the size or
proportions of a control.. By dragging out from the centre of the control, the object
becomes larger. When you drag towards to centre of a control, the control becomes
smaller. When you resize a control, you change its dimensions, not the size of the text.
Procedures
1. Click the control you want to resize.
2. Drag the sizing handles as required to make the control bigger or
smaller.
3. Release the mouse button.
DELETING A CONTROL
Procedures
1. Select the control.
2. Press the [Delete] key.
Procedure
1. Hold the mouse pointer over the control and right click.
2. Select Properties.
3. Type into the LinkedCell control the cell reference (eg. A5, B16, D32)
that you want the selected value to be returned to.
If the cell is on a different sheet to the control, include the sheet name
(as shown in the tab at the bottom) followed by an exclamation mark (!)
before the cell reference, eg.
Regions!A10
…will return the control’s value to cell A10 on the sheet named Regions
of the workbook.
4. Close the Properties window.
5. Click the Design Mode button on the Control Toolbox toolbar (Excel
2000-2003) OR click the Design Mode button in the Controls group of
the Developer tab (Excel 2007).
6. Test/use the control.
The second thing to note is the rest of the procedure name. This name will depend on
the control that has been double clicked and describes the event that triggers the
procedure. The default event usually given to most controls is “Click” or “Change” ..
In the example below, a check box has been double clicked.
By selecting a different event from the list, the check box can be made to do something
under different circumstances. In the example below, the event has been changed to
Change.
Procedures
1. Double click the control.
2. Select the appropriate event for which you want to write a procedure.
3. Enter the relevant code.
4. Return to Excel and test/use the control.
The table below lists the more commonly used events and the controls that they apply
to.
Event Control Occurs
Change Check Box, List Box, Occurs when the value
Combo Box, Spin Button, property of a control
Option Button, Text Box , changes.
Scroll Bar
Click Check Box, List Box, When the user points to a
A List Box
Procedures
Excel 2000 - 20003 Excel 2007
1. Show the Control Toolbox 1. Show the Developer tab if
toolbar. necessary (see item 1 in the
procedure on page 42).
Click the Insert button in the
Controls group.
2. Click the List Box button 2. Click the List Box button
on the toolbar. The mouse under ActiveX controls. The
pointer changes to a small mouse pointer changes to a small
crosshair. crosshair.
3. Drag the mouse pointer over the area on the worksheet where you want
to create the List Box.
4. Release the mouse button.
5. Create a named range on a worksheet, listing the items that you want to
appear in the list box. The worksheet can be anywhere in the workbook
that you are creating the control in. The list must be laid out vertically
(ie. down a column NOT across columns).
6. Hold the mouse pointer over the spin button and right click.
7. Select Properties.
8. Type into the ListFillRange property the named range created in 5
above.
9. Press Enter.
10. Close the Properties window.
Procedures
Excel 2000 - 20003 Excel 2007
1. Show the Control Toolbox 1. Show the Developer tab if
toolbar. necessary (see item 1 in the
procedure on page 42).
Click the Insert button in the
Controls group.
Spin Button
Procedures
Excel 2000 - 20003 Excel 2007
1. Show the Control Toolbox 1. Show the Developer tab if necessary
toolbar. (see item 1 in the procedure on page
42).
Click the Insert button in the
Controls group.
Procedures
Excel 2000 - 20003 Excel 2007
1. Show the Control Toolbox 1. Show the Developer tab if
toolbar. necessary (see item 1 in the
procedure on page 42).
Click the Insert button in the
Controls group.
6. Hold the mouse pointer over the control and right click.
7. Select Properties.
8. Type into the ListFillRange property the named range created in 5 above.
9. Press Enter.
10. Close the Properties window.
EXERCISE
AUTOMATING A WORKSHEET WITH ACTIVEX CONTROLS
Task – Execute data entry by using a drop-down list, spinner and heck box
5. Create a named range called StockList using the data in cells A1 to B7 of Sheet2 (this
data is imported from the Web and automatically updated every 10 minutes).
6. Set up Properties and code for the three controls as follows:
7. Turn off Design Mode and test that the controls function as expected. Formulas already
exist in cells B7 and B10 for calculation of the results.
8. Write code to the Workbook “Open” event that protects Sheet1 for UserInterfaceOnly.
9. Save and close the workbook.
10. Re-open the workbook and check that the controls and protection functions as expected.
You should only be able to enter values using the ActiveX Controls.
11. Save and close the workbook.
OVERVIEW
Discussion
In the preceding two chapters, a start was made at understanding “events” and how to
associate VBA code to them.
Essentially, an event occurs when a user makes something “happens” on their
computer. The commonest way of creating an event is by clicking a button on the
screen or pressing a key on the keyboard, thus triggering a command. When you click a
macro button, you are initiating an event (ie. the macro runs). Hence, an “event
procedure” is a piece of code that automatically executes when an event is triggered.
Not all events are user initiated; some are triggered by the computer itself through a
timer, (eg. an appointment or task reminder popping up in Outlook). Others are set off
during, just before or just after certain actions take place in a workbook or on a
worksheet, such as a file being opened or saved or a change made to a range. They can
also occur when a procedure or macro carries out the actions above.
The events that we will be examining in this lesson are:
a) those associated with a worksheet, eg. when a cell is selected on a sheet or the
sheet is recalculated;
b) those associated with the workbook itself, eg. when a new one is created, saved
or activated; and
c) those that trigger automatically, eg. using a timer.
TYPES OF EVENT
Discussion
The table below list events associated with worksheets and workbooks and explains
when they are triggered.
TABLE A : WORKSHEET EVENTS
Event Triggers when…
Activate The worksheet is activated.
BeforeDoubleClick The worksheet is double-clicked.
BeforeRightClick The worksheet is right-clicked.
Calculate The worksheet is calculated (or recalculated).
Change Cells on the worksheet are changed by the user.
Deactivate The worksheet is deactivated.
FollowHyperlink A hyperlink on the worksheet is clicked.
PivotTableUpdate A PivotTable on the worksheet has been updated.
SelectionChange The selection on the worksheet is changed.
As well as writing event procedures in the correct location, they must be given their
correct, reserved name. The naming convention for an event procedure associated with
a worksheet is as follows:
Worksheet followed by an underscore followed by the appropriate event name as
listed in Table A above, eg.
Worksheet_Activate or Worksheet_SelectionChange
Although you can type the name of the procedure yourself, it is more convenient and
safer (to prevent typos) to let the VB Editor enter the name for you.
This can be achieved by selecting in the Project Explorer the object that you want to
write the procedure into, and then selecting the procedure name from the drop down
list at the top of the code pane.
Procedures
1. Launch the VB Editor.
2. Identify in the Project Explorer pane the VBAProject
containing the worksheet or workbook object that you want to
write an event procedure for.
3. Double click the object.
4. Select Worksheet or Workbook from the drop down list at the
top left of the code pane.
5. Select the appropriate event name from the drop down list at
the top right of the code pane.
6. Write code as necessary.
End Sub
Or, a simple event procedure confirming that the correct workbook has been opened
could be assigned to the Workbook_Open event as follows:
MsgBox "This workbook contains sales data for Quarter 1 2010 only"
End Sub
wn represents the window that has just been activated, so if you want your event
procedure to carry out some action(s) to that window, you refer to it as wn.
In the following example, whenever a window is activated in the current workbook, it
is maximised and given a caption (title) of Active Window.
Private Sub Workbook_WindowActivate(ByVal Wn As Window)
Wn.WindowState = xlMaximized
Wn.Caption = "Active Window"
End Sub
Wn.WindowState = xlMinimized
Wn.Caption = ThisWorkbook.Name
End Sub
End Sub
Some events come with a Cancel argument. This is normally used in conjunction with
an IF statement to cancel the associated event procedure if unfavourable conditions are
encountered. In the example below, the Workbook_BeforeClose event is cancelled if
there is no data entered in cell 1 of sheet 1.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If IsEmpty(Sheets("Sheet1").Range("A1")) Then
MsgBox "Cannot close this file unless data is entered in cell A1 of Sheet 1"
Cancel = True
End If
End Sub
End Sub
The BeforeClose is equally useful for cleaning up and/or restoring data or settings
when closing a file.
Other useful workbook events are those associated with sheets such as, SheetActivate
and NewSheet. The following example ensures that cell A1 is always selected when a
different sheet in the current workbook is activated.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Range(“A1”).Select
End Sub
The On Error Resume Next statement prevents a runtime error occurring if the sheet
being activated does not contain cell A1 (eg. it is a chart sheet).
The following enters and formats a heading in cell A1 of all new sheets added to the
workbook.
End If
End Sub
On this occasion, a simple IF statement is used to evaluate the type of sheet being
inserted to ensure that a runtime error is not generated if, for example, a chart sheet is
inserted.
Worksheet
A popular event associated with a sheet is SelectionChange. The following example,
colours the cell being selected, thus making it easier to identify.
' Removes any current interior colour from the current sheet
Cells.Interior.ColorIndex = xlNone
End Sub
Unlike the events covered previously in this lesson, the OnTime method is made use of
in a standard procedure on a general module sheet.
The OnTime method is a member of the Application object, hence the syntax for its use
is:
Application.OnTime
EarliestTime: Required - The time when you want this procedure to be run.
Procedure: Required - The name of the procedure to be run.
LatestTime: Optional - The latest time at which the procedure can be run. For example,
if LatestTime is set to EarliestTime + 30 and Microsoft Excel is not in Ready, Copy, Cut,
or Find mode at EarliestTime because another procedure is running, Microsoft Excel
will wait 30 seconds for the first procedure to complete. If Microsoft Excel is not in
Ready mode within 30 seconds, the procedure won’t be run. If this argument is
omitted, Microsoft Excel will wait until the procedure can be run.
Schedule: Optional - True to schedule a new OnTime procedure. False to clear a
previously set procedure. The default value is True.
EarliestTime and LatestTime can be set using the time expressed as a fraction of a day.
For example:
Because it is difficult to calculate times out as fractions of a day, the easiest way of
entering the times is by using the TimeValue function. This allows you to enter the
time in a more understandable hours, minutes and seconds format. For example, 3pm
could be expressed as TimeValue (“15:00:00”).Hence:
The examples above allow you run a procedure at a specific time in the future. By
using the NOW function in conjunction with TimeValue, you can run a procedure
after a specific time have elapsed. For example, NOW + TimeValue(“00:01:00”) will
calculate a time of one minute from when the procedure is initiated.
Hence:
… will run MyProcedure one minute from when the statement is executed. So if the
statement is executed at 13:45, MyProcedure will run at 13:46.
You also can the OnTime method to schedule a procedure on a particular day but to do
this, you must keep your computer turned on with Excel active and, of course, you
must remember to run the procedure that contains the OnTime method before leaving!
EXERCISE
HANDLING EVENTS WITH VBA
3. Add code to the appropriate event (Tip: it’s a workbook one) to display the splash
screen when the workbook opens.
4. Add code to another event to close the form after 3 seconds (Tip: it’s one of the form
events – 3 seconds after what does the form have to close? Look through the list of form
events).
OVERVIEW
Discussion
While it is true that the macro recorder does a pretty good job of creating and formatting
charts, it does not always do it in the most effective and efficient way. This lesson
therefore will look at some simple and useful ways of enhancing the code created by
the recorder and adding code to carry out additional tasks that the recorder cannot
manage.
There are so many chart objects, that a comprehensive explanation of them all would
stretch to dozens of pages. The examples here, therefore, gives a few simple VBA
techniques to create charts, move and size them and add or remove series and add/edit
their formatting and structure. The code shown is also useful because it can be used to
program Microsoft Chart; the applet used by other Office applications to create charts
for them (eg. in a PowerPoint slides).
CREATING CHARTS
Discussion
The recorder uses quite a roundabout method to create an embedded chart (one that is
located on a worksheet alongside the data). It first creates a default chart on a separate
chart sheet, makes changes to it as necessary and then relocates it to the required
worksheet. It places it in the default location (centre of work area) and uses the default
size (approximately a quarter of the work area).
The recorded code below creates an embedded clustered bar chart using just the first
step of the Chart Wizard (ie. clicking Finish after selecting the chart type):
Sub CreateChart()
Charts.Add
ActiveChart.ChartType = xlBarClustered
ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("A2:E5")
ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
End Sub
Although the code does the job, it is rather inflexible in as much as it will always create
the chart using the same data (Sheet1 A2:E5) and locate it on the same sheet (Sheet1).
To make the procedure create the chart from ANY data on ANY sheet and always place
it on the same sheet as the data, you need to create a couple of variables to:
a) Store the selected data as a range object; and
b) Store the active sheet name as a string.
The variables can then be used as arguments for the SetDataSource Source:= and
Location Name:= arguments in place of the absolute references created by the recorder.
Eg:
Sub CreateChart()
Charts.Add
ActiveChart.SetSourceData Source:=chtData
ActiveChart.ChartType = xlBarClustered
ActiveChart.Location Where:=xlLocationAsObject, Name:=chtSht
End Sub
This is a good way of creating a procedure that acts like a template, always giving you
a consistent chart in a “house” style.
The procedure also works if chtData is a non-contiguous range.
End Sub
Not only does this use absolute references for the sheet and the range (although this
can be rectified as outlined in the previous topic), it also refers to the chart as Chart 1;
again, an absolute reference lacking flexibility should you wish to run this macro on a
different chart. Also, the methods used to move and size the charts are difficult to
understand and edit.
Hence, the solution is NOT to use the same code as the recorder but to write your own
VBA using the ChartObjects object.
This is because ChartObjects.Add produces a chart equally as well as Charts.Add but
allows you to enter arguments for positioning and sizing the chart as it is created. This
is because an embedded chart is contained in a ChartObject and it is the ChartObject
that has the size and location properties. The chart inside the ChartObject is what you
access to change most of the other properties.
And because a ChartObject can be created on an active sheet and a chart then put
directly inside it, there is no need to create the additional variables in the previous
examples. Hence, it produces much cleaner, more understandable code.
The example below, creates a clustered column chart on the same sheet that the data is
selected from. It positions the chart in the top left hand corner of the work area (Left:=
0 and Top:= 0) and sizes it to 375 pixels wide by 225 pixels high. The actual size of the
chart will depend on the resolution set on the computer monitor.
Sub AddPositionAndSizeChart()
End Sub.
You may find it more convenient, in a longer procedure, to define an object variable for
the new chart created. Thus, if you need to refer to this chart later in the procedure, you
can conveniently use the variable name.
The following example does the same as the two above, but sets a ChartObject variable
for the new chart added.
Sub AddPositionAndSizeChart()
Dim myCht As ChartObject
myCht.Chart.SetSourceData Source:=Selection
myCht.Chart.ChartType = xlColumnClustered
End Sub
In the same way as you can set a chart object’s size and position properties at its creation,
you can position or size the chart at any time by changing the same properties. The
following identifies a specific chart object and moves and sizes it:
Sub ResizeAndRepositionChart()
With ActiveSheet.ChartObjects(“Chart 1”)
.Left = 100
.Width = 375
.Top = 75
.Height = 225
End With
End Sub
The following does the same as above but to an active chart. Remember, it is not the chart
that has the sizing and positioning properties, it is its container - the chart object. Hence, in
this case, you have to refer to the chart object as the parent of the chart. Confusing?.........yes!
Sub ResizeAndRepositionChart()
With ActiveChart.Parent ' The ChartObject is the chart's parent
.Left = 100
.Width = 375
.Top = 75
.Height = 225
End With
End Sub
Rather than calculating a chart’s position using pixels, you can cover a specified range with a
chart. The following procedure places a chart over the range D5:K25:
Sub CoverRangeWithChart()
Dim cht As Chart Object
Dim rng As Range
cht.Left = rng.Left
cht.Width = rng.Width
cht.Top = rng.Top
cht.Height = rng.Height
End Sub
End Sub
If you have many charts on a worksheet, you may like to arrange them ALL neatly. The
following procedure loops through any number of charts, resizes them the same and
arranges them in regular rows and 3 columns:
Sub ArrangeMyCharts()
Dim iChart As Long
Dim nCharts As Long
Dim dTop As Double
Dim dLeft As Double
Dim dHeight As Double
Dim dWidth As Double
Dim nColumns As Long
NAMING A CHART
Discussion
Charts created on their own sheet are easily identified by their sheet name. For
example, Charts(“Chart1”).Activate will activate the chart on the sheet named Chart1.
Any changes that you wish to make to that chart can then be referred to as
ActiveChart, eg.
ActiveChart.PlotArea.Interior = vbCyan
ActiveChart.ChartArea.Interior = vbYellow
ActiveChart.Name = “South RegionSales”
Excel, however, gives embedded charts a unique name when they are created. The first
chart on a sheet is named “Chart 1”; the next one “Chart 2” and so forth (there is a
space between Chart and the number). The names are based on a sheet-by-sheet basis
hence, you may have several Chart 1s in a workbook.
This can make it difficult to identify a specific chart that you want your VBA to act
upon. As a result, it may be advantageous to give it a name of your own.
It is also important to note that it is NOT the embedded chart itself that is named but its
container - the ChartObject. The examples below name embedded charts under various
circumstances
End Sub
As with other examples in this lesson, you can set an object variable for the new chart
series being added. The following procedure assigns the variable myNewSer to the
new chart series created.
Sub AddNewSeries()
Dim MyNewSrs As Series
Set MyNewSrs = ActiveChart.SeriesCollection.NewSeries
With MyNewSrs
.Name = "April"
.Values = "=Sheet1!Apr_Sales"
End With
End Sub
EXERCISE
CHARTING WITH VBA
Tasks - To create and modify charts using VBA and ActiveX controls
There are few practical examples of using the PivotTables collection but one might be:
numPt = ActiveSheet.PivotTables.Count
… stores in the variable numPt the number of Pivot Tables on the active sheet.
There are, however, many practical examples of using the Pivot Table object singly, eg.
ActiveSheet.PivotTables(“MyPivot”).RefreshTable
… updates the named Pivot Table with any changes made to the source data
ActiveSheet.PivotTables("MyPivot1").RowGrand = False
ActiveSheet.PivotTables("MyPivot1").ColumnGrand = False
… removes row and column grand totals from the named Pivot Table (TRUE will add
the grand totals).
ActiveSheet.PivotTables("MyPivot1").Format xlReport4
… adds the Report 4 AutoFormat style to the named Pivot Table.
ActiveSheet.PivotTables("MyPivot1").PivotSelect ""
… selects the entire named Pivot Table. That could then be followed by:
Selection.Clear or
Selection.Copy or
Selection.Font.Name = “Calibri”
… or any one of many other properties and methods applicable to a Pivot Table.
1. Set a “Pivot Cache” to store the source data for the Pivot Table. A “cache” is a
temporary store for a copy of the original data. This cache can later be used in the
same procedure for producing other Pivot Tables from the same source. The code
for creating a Pivot Cache is as follows:
ActiveWorkbook.PivotCaches.Add (arguments)
The Add method above takes two arguments:
SourceType The type of data being used, viz.
xlConsolidation
xlDatabase
xlExternal
xlPivotTable
xlScenario
Hence, the statement below sets a Pivot Cache named pvCsh that contains data from
an Excel list or table that is stored on the sheet named Data in cells B2 to H20:
Set pvCsh = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:=Sheets("Data").Range("B2:H21"))
2. Create the basic Pivot Table “skeleton”. The code, assuming the Pivot Table is being
created on the sheet that the macro is being run from, is as follows:
Activesheet.PivotTables.Add (arguments)
The Add method above takes four arguments, although only the first two are required.
PivotCache (Required) The source data for the Pivot Table. This will be the
Hence, the statement below will add from the cache named pvCsh, a Pivot Table
starting in cell A30 of the active sheet, and name it MyPivot1.
ActiveSheet.PivotTables.Add PivotCache:=pvCsh, _
TableDestination:=Range("A30"), TableName:="MyPivot1"
ActiveSheet.PivotTables("MyPivot1").PivotFields("Region").Orientation =
xlRowField
ActiveSheet.PivotTables("MyPivot1").PivotFields("Product").Orientation =
xlColumnField
ActiveSheet.PivotTables("MyPivot1").PivotFields("Sales").Orientation =
xlDataField
These three statements could be abbreviated using a With… End With block as
follows:
With ActiveSheet.PivotTables("MyPivot1")
.PivotFields("Region").Orientation = xlRowField
.PivotFields("Product").Orientation = xlColumnField
.PivotFields("Sales").Orientation = xlDataField
End With
The example below creates a Pivot Table using the data in cells B2 to H20 and places
the Pivot Table in the cell A30 on the same sheet. The entire procedure, therefore, for
creating the Pivot Table described above is:
Sub CreatePivotTable()
Dim pvCsh
Set pvCsh = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:=Sheets("Data").Range("B2:H21"))
ActiveSheet.PivotTables.Add PivotCache:=pvCsh, _
TableDestination:=Range("A30"), TableName:="myPivot1"
With ActiveSheet.PivotTables("MyPivot1")
.PivotFields("Region").Orientation = xlRowField
.PivotFields("Product").Orientation = xlColumnField
.PivotFields("Sales").Orientation = xlDataField
End With
End Sub
While the code above may seem tedious to write, it compares favourably to the
example below that creates the same Pivot Table using the macro recorder.
Sub MakePivotTable()
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase,
SourceData:= _
"Sheet1!A1:G60").CreatePivotTable TableDestination:="", TableName:=
_ "PivotTable1", DefaultVersion:=xlPivotTableVersion10
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Salesperson")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Product")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField
ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Sales"), "Sum of Sales", xlSum
End Sub
Hence, if there are two Pivot Tables on a sheet, the “oldest” (the one created first)
will have an index number of two. The “newest” Pivot Table will always have an
index number of 1.
To add to the confusion, if a sheet contains, lets say, three Pivot Tables, index
numbers 1, 2, and 3 and the second one to have been created is removed, the
one that had index number 3 gets renumbered to index number 2.
This can make it very difficult to identify individual Pivot Tables but proves
useful in looping through them using a For… Next statement block.
2. By a name expressed as a string (ie. as text). When you create a Pivot Table using
the Wizard, you are not given the opportunity of naming it. Excel, therefore, gives
it a default name - PivotTable followed by a sequential number.
This is in sharp contrast to the index number, because the FIRST Pivot Table
created is given a name of PivotTable1, the second Pivot Table is named
PivotTable2 and so on.
Names of Pivot Tables are retained in the file that they were created, so even if
you remove ALL the Pivot Tables on a sheet, the name of the next one created
will always be named in sequence to the last one. Hence, you may have only one
Pivot Table on a sheet, but its name could be PivotTable12. And to add to the
confusion further, Pivot Tables names are numbered on a workbook basis,
whereas index numbers are added on a sheet-by-sheet basis.
All this goes to show that it is advantageous when writing code that creates Pivot
Tables, to give each one an easily identifiable name.
As shown in the example on page 96, a Pivot Table can be named when using VBA to
create it. But in order to rename an existing Pivot Table, the Pivot Table has to be
identified individually and then given a Name property, eg.
A useful piece of code for referring to a Pivot Table that has had a cell selected on it is:
ActiveCell.PivotTable
Hence,
ActiveCell.PivotTable.Name = “Sales by Year and Month”
… would rename a selected Pivot Table.
rows, column or data. PivotField can be used in a similar way to move, remove or add
fields to a Pivot Table structure.
The examples below give the necessary code to undertake a variety of tasks on Pivot
Fields.
This results in the Year field (currently in position 1) being moved to become a sub
grouping of Region (position 2 in the hierarchy of levels). The pictures below show the
effect of moving the Year field to position 2.
NOTE: When refreshing a Pivot Table, ALL Pivot Tables in a workbook that are based
on the same data source (Pivot Cache) are simultaneously refreshed. It may not be
necessary, therefore, to loop through them all as shown above.
EXERCISE
WORKING WITH PIVOT TABLES IN VBA
Part of the code is already written for you. The sub procedure, CreatePivotAnalysis,
creates a PivotCache from the data and on the SurveyData sheet and produces the first
Pivot Table for the “Store locations are convenient” question. Expand this procedure
using the information in the table above, to produce Pivot Tables for the other three
questions as shown in the screen shot above.
Test and debug the code.
Add code to replace 1, 2, 3, 4 and 5 with Strongly Disagree, Disagree, Undecided,
Agree, Strongly Agree. (Tip: Use ActiveSheet.Range("A:A").Replace "1" , “Strongly
Disagree” and repeat for each option).
Test and debug the code.
The ChangeToPercent sub procedure on module sheet 2 of this workbook is designed
to change the type of calculation performed in the data area of a Pivot Table to a
percentage of the column.
Modify this sub procedure so that it runs on ALL Pivot Tables on an active sheet (Tip:
Use a loop).
Repeat 6 above for the ChangeToCount sub procedure.
Test and debug the code.
Finally, call into the CreatePivotAnalysis sub procedure, the sub procedure named
MakeButtons. This creates two macro buttons to run the ChangeToPercent and
ChangeToCount.
Assign the CreatePivotAnalysis sub procedure to the button on the SurveyData sheet.
Run the CreatePivotAnalysis sub procedure.
Test and debug the code.
Save and close the workbook.
OVERVIEW
Discussion
Automation (formerly OLE Automation) is a feature that programs use to expose their
objects to development tools, macro languages, and other programs that support
Automation. For example, a spreadsheet program may expose a worksheet, chart, cell,
or range of cells, each as a different type of object. A word processor might expose
objects such as an application, a document, a paragraph, a sentence, a bookmark, or a
selection.
When a program supports Automation, you can use Visual Basic for Applications to
access the objects it exposes. You manipulate these objects in Visual Basic by invoking
methods on the object or by getting and setting the object's properties. We will look at
working with other Microsoft Office programs.
There are four main steps to automating another Office application (where * is the
name of the application, eg. Word, Excel, PowerPoint, Access, Visio or Outlook).
Add a reference to the application’s object library.
Declare a variable as a * object type.
Assign the object returned by the CreateObject function to the object variable
(application) you declared in step 2.
Use the properties and methods of the object variable to automate *
Procedures
1. Launch the VB Editor.
2. Select the Tools menu.
3. Select References….
4. In the list of Available References:, click to select the relevant
check box.
5. Click OK.
Procedures
1. Launch the VB Editor.
2. Identify in the Project Explorer pane the VBAProject that you
wish to write the procedure in.
3. Add a module to the project or activate an existing module
sheet.
4. Start a new sub procedure.
5. Declare (dimension) the object variable that you intend using
in the sub procedure. Use the examples above as a guide.
Or…
The following example binds the wrdApp variable to a specific Word document.
Dim wrdApp As Word.Document
Set wrdApp = GetObject("s:\SharedDocs\Report.doc")
The following example binds the wrdApp variable to an existing instance of Word
Dim wrdApp As Word.Document
Set wrdApp = GetObject( , “Word.Application”)
EXAMPLES
Below are some simple examples for automating Word, PowerPoint and Outlook.
1. The following sample macro uses automation to create a Word object, create a new
document, add some text, and save the document.
Sub AutomateWord()
End Sub
EXERCISE
CONTROLLING AND COMMUNICATING WITH OTHER APPLICATIONS
Code Message
3 Return without GoSub
5 Invalid procedure call
6 Overflow
7 Out of memory
9 Subscript out of range
10 This array is fixed or temporarily locked
11 Division by zero
13 Type mismatch
14 Out of string space
16 Expression too complex
17 Can't perform requested operation
18 User interrupt occurred
20 Resume without error
28 Out of stack space
35 Sub, Function, or Property not defined
47 Too many code resource or DLL application clients
48 Error in loading code resource or DLL
49 Bad code resource or DLL calling convention
51 Internal error
52 Bad file name or number
53 File not found
54 Bad file mode
55 File already open
57 Device I/O error
58 File already exists
59 Bad record length
61 Disk full
62 Input past end of file
Example A Example B
To make the message box interactive, the arguments must be put inside brackets. The
following code will display Example A above.
MsgBox ("Do you want to continue deleting the data", vbYesNo, "Delete Confirm")
Prompt B T
The buttons argument consists of constants or values from each of the following three
groups:
Icon style:
Constant Value Display Icon
Default Button:
Constant Value Default
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 third button is default
The buttons argument of the message box function can hold three pieces of information
separated by a plus (+) symbol. Using the following code as the buttons argument will
produce Example C below.
vbQuestion
vbYesNo vbDefaultButton2
(second from left)
A more concise method of writing the above sample of code would be to use the
numeric values for the arguments, eg.
4 + 32 + 256
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type a variable name to store the value of whichever button is
clicked in the message box, eg. response.
3. Type =.
4. Type MsgBox.
5. Type an opening bracket ( .
6. Type a speech mark (Shift 2).
7. Type a prompt for the message box, ie. the message that you
want it to display, eg. Do you want to continue?
8. Type a speech mark (Shift 2).
9. Type a comma.
10. Type the necessary value to indicate which buttons you want
the message box to display, eg. vbYesNo.
11. If you wish to add an icon If you do not wish to add an
and/or default button to the icon and/or a default button to
message box, type a plus the message box, go to 15
symbol (+). below.
12. Type the necessary value to
indicate which icon to
display, eg. vbQuestion
13. Type a plus symbol (+).
14. Type the necessary value to
indicate which default
button you wish to set,
eg.vbDefaultButton2
15. Type a comma.
16. If you wish to add a title to If you do not wish to add a title
the message box, type a to the message box, go to 20
comma below.
17. Type a speech mark (Shift
2).
18. Type the title text.
19. Type a speech mark (Shift
2).
20. Type a closing bracket ) .
21. Press Enter.
22. Add additional code as necessary.
vbYes 6 Yes
vbNo 7 No
In the following example, the message box offers a yes/no response. If the user clicks
yes, then the procedure will delete all the data from the sheet. If the user clicks no, the
procedure will terminate.
If MsgBox (“Do you want to delete all data”, vbYesNo + vbCritical) = vbYes
Then
ActiveSheet.Cells.Clear
End If
The result of the message box (ie. whether the yes or no button is clicked) can be stored
in a variable and the code could also be written:
Procedures
1. (The procedure below assumes a message box containing Yes
and No buttons. It can be adapted, however, to respond to any
set of buttons (eg. vbOKCancel, vbRetryCancel etc.))
2. Position the cursor in the sub procedure code where you want
to place the statement.
3. Create an interactive message box as described in the previous
topic of this lesson.
4. Press Enter.
5. Type If.
6. Type a space.
7. Type the variable name that you have used to store the
response from the message box.
8. Type a space.
9. Type = vbYes.
10. Type a space.
11. Type Then.
12. Type the statements that you want the sub procedure to
perform if the user has clicked the Yes button.
13. Press Enter.
14. Type Else.
15. Press Enter.
16. Type the statements that you want the sub procedure to
perform if the user has clicked the No button.
17. Press Enter.
18. Type End If.
19. Press Enter.
20. Add additional code as necessary.
Sub CircData()
Const PI = 3.142
Radius = InputBox("Type the radius of your circle in centimetres", "Circle Data")
If IsNumeric(Radius) Then
CircArea = PI * (Radius ^ 2)
CircCircumf = 2 * PI * Radius
MsgBox "The area of the circle is: " & CircArea & vbCrLf & vbCrLf & _
"The circumference of the circle is: " & CircCircumf
Else
MsgBox "Input not valid"
End If
End Sub
Sub DeleteOldFile()
Dim fileToRemove As String
On Error GoTo errhandle
fileToRemove = InputBox("Type name of file to delete from the current folder", "Delete
File")
If fileToRemove = "" Then
Exit Sub
Else
Kill ThisWorkbook.Path & "\" & fileToRemove & ".xls"
MsgBox "File successfully deleted"
End If
Exit Sub
errhandle:
If Err.Number = 53 Then
response = MsgBox("File not found. Do you want to try again?", vbYesNo)
If response = vbYes Then
fileToRemove = InputBox("Type name of file to delete from the current folder",
"Delete File")
Resume
End If
End If
If Err.Number = 70 Then
MsgBox "File is currently open. Close the file and run the macro again"
End If
End Sub
Dim origVal
Dim origCel
Sub temp()
cht.Chart.ChartArea.Interior.Color = vbCyan
cht.Chart.ChartArea.Font.Size = 12
cht.Chart.PlotArea.Interior.Color = vbYellow
cht.Chart.SeriesCollection(1).Interior.Color = vbMagenta
End Sub
Sub CreateCharts()
Dim chartRange1 As Range
Dim chartRange2 As Range
Sub CreatePivotAnalysis()
Dim pvCsh As PivotCache
Set pvCsh = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase,
SourceData:=Sheets("SurveyData").Range("A1:F101"))
Sub ChangeToPercent()
For Each PT In ActiveSheet.PivotTables
With PT.DataFields(1)
.Calculation = xlPercentOfColumn
.NumberFormat = "0.00%"
End With
Next
End Sub
Sub ChangeToCount()
For Each PT In ActiveSheet.PivotTables
With PT.DataFields(1)
.Calculation = xlNormal
.Function = xlSum
.NumberFormat = "General"
End With
Next
End Sub
Sub MakeButtons()
Dim percBut As Button
Dim countBut As Button
Set percBut = Sheets("Summary").Buttons.Add(400, 25, 100, 40)
percBut.OnAction = "ChangeToPercent"
percBut.Characters.Text = "Change to percent"
Set countBut = Sheets("Summary").Buttons.Add(400, 90, 100, 40)
countBut.OnAction = "ChangeToCount"
countBut.Characters.Text = "Change to count"
End Sub
Sub TalkToWord()
Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")
Selection.Copy
With WordApp
.Visible = True
.Documents.Add
With .Selection.Font
.Bold = True
.Size = 18
End With
With .Selection
.TypeText "Quarter 1 Sales"
.ParagraphFormat.Alignment = 1
.typeparagraph
.typeparagraph
.Paste
End With
.Quit
End With
End Sub
INDEX
A Events
arguments ...................................................... 60
ActiveX Controls
cancel argument ............................................. 61
Adding to worksheet ...................................... 42
examples ....................................................... 61
check box ....................................................... 42
non object ...................................................... 63
combo box ............................................... 47, 52
OnTime ......................................................... 63
Control toolbox .............................................. 39
types .............................................................. 56
deleting .......................................................... 45
events ...................................................... 47, 48 F
list box ........................................................... 49
Form Controls
moving and sizing .................................... 44, 45
Definition ...................................................... 39
option buttons ................................................ 50
Forms toolbar ................................................ 39
Properties ....................................................... 41
returning a value ............................................ 46 I
spin button ..................................................... 51
Automation IsNumeric .................................................... 8, 102
adding a reference to object library ................. 88 M
declaring an MS Office object variable ........... 89
defintion ........................................................ 88 Message Box
setting an MS object variable .......................... 90 adding interactivity ........................................ 97
button types ................................................... 97
C default buttons ............................................... 98
Charts icons.............................................................. 97
interactive use examples ................................ 99
creating in VBA ............................................. 67
moving and sizing .......................................... 68 responding to ................................................. 99
multiple ......................................................... 71 P
naming........................................................... 72
series adding .................................................. 73 Pivot Tables
series, deleting ............................................... 74 creating in VBA............................................. 78
moving fields................................................. 81
D naming .......................................................... 80
overview........................................................ 77
Dialog Boxes
using Excel dialog boxes in procedures........... 21 pivot cache .................................................... 78
refreshing ...................................................... 83
E removing fields .............................................. 82
Error Handling R
Err.Number .................................................... 13
error descriptions ........................................... 16 Run-time error ................................................... 7
labels ............................................................. 11 U
On Error GoTo........................................... 9, 11
On Error GoTo 0 ............................................ 16 Userforms, custom
On Error Resume Next ............................... 9, 10 adding controls .............................................. 22
Resume ...................................................... 9, 11 adding events to controls................................ 28
trapping with error numbers ........................... 13 Cancel button ................................................ 29
using interactive message boxes ..................... 12 check boxes ................................................... 31
using the IF statement.......................................7 combo boxes.................................................. 30
Error handling, IS... functions control properties ........................................... 26
IsArray.............................................................8 control types .................................................. 22
IsDate ..............................................................8 creating ......................................................... 21
IsEmpty ...........................................................8 displaying ...................................................... 33
IsError .............................................................8 editing controls .............................................. 24
IsMissing .........................................................8 form events - initialize ................................... 32
IsNull...............................................................8 grouping controls ........................................... 25
IsNumeric ........................................................8 inserting to a workbook.................................. 22
IsObject ...........................................................8 list boxes ....................................................... 30
Event Procedures naming .......................................................... 27
definition ....................................................... 56 OK button...................................................... 29