0% found this document useful (0 votes)
36 views

VBA Training 2

Uploaded by

maria.isla.bbc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

VBA Training 2

Uploaded by

maria.isla.bbc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 188

QAVBA10INT v1.

3 Introduction to VBA – Office 2010

Copyright Statement
QA Limited owns all copyright and other Intellectual Property Rights and asserts
its moral right to be regarded as the author of this material. All rights reserved. No
part of this publication may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means electronic, mechanical, photocopying,
recording or otherwise, without prior written permission of the copyright owner.
Contents may be subject to change at the discretion of QA Limited and without
notice.

QA Limited shall not be liable in any way in respect of any loss, damages, costs,
liabilities or expenses suffered by the user, whether directly or indirectly as the
result of the content, format, presentation or any other use or aspect of the
Materials. The user shall not make, give or supply any guarantee, warranty or
other undertaking as to the appropriateness or other attributes of Materials or the
Course which binds or purports to bind QA limited or its Affiliates.

The operating systems and applications used for the purpose of fulfilling QA
training events or referred to in this courseware are used for demonstration
purposes only.

Copyright © 2013 QA Limited

All Rights Reserved


Introduction to VBA – Office 2010 QAVBA10INT v1.3

Contents
Introduction and Welcome .................................................................................... 1
Module 1 - Getting Started .................................................................................... 2
Topic A - Introducing Visual Basic for Applications ............................................ 2
Topic B - Recording a Macro ............................................................................. 4
Topic C - Running a Macro ................................................................................ 6
Topic D - Absolute or Relative Cell Referencing ................................................ 9
Topic E - Saving and Opening Files with Macros ............................................ 11
Topic F - Adding Macros to Keyboard Shortcuts, QAT and Buttons ................ 14
Topic G - Editing a Macro in the Visual Basic Editor ....................................... 21
Topic H - Understanding the Development Environment ................................. 22
Topic I - Customising the Editor ....................................................................... 24
Topic J - Tips for General Typing in VBA......................................................... 26
Topic K - Using Visual Basic Help ................................................................... 27
Module 2 - Working with Procedures .................................................................. 32
Topic A - Program Design ............................................................................... 32
Topic B - Understanding Modules ................................................................... 33
Topic C - Creating a Module ............................................................................ 34
Topic D - Understanding Procedures............................................................... 34
Topic E - Programming Macro Concepts ......................................................... 35
Topic F - Creating a Subroutine ....................................................................... 37
Topic G - Creating a Function .......................................................................... 40
Topic H - Understanding Arguments ............................................................... 44
Topic I - Exiting Procedures............................................................................. 46
Topic J - Calling Procedures............................................................................ 47
Module 3 - Understanding Objects, Properties, Methods, and Events ................ 51
Topic A - Understanding Objects Properties, Methods and Events ................. 51
Topic B - Navigating the Object Hierarchy ....................................................... 52

Page i
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic C - Understanding Collections ................................................................ 53


Topic D - Accessing a Member of a Collection ................................................ 54
Topic E - Understanding Hierarchy .................................................................. 57
Topic F - Using the Object Browser ................................................................. 59
Topic G - Using the With Statement ................................................................. 62
Topic H - Working with Properties.................................................................... 65
Topic I - Working with Methods ........................................................................ 69
Topic J - Creating an Event Procedure ............................................................ 71
Topic K - Reserved Macro Names ................................................................... 72
Module 4 - Using Expressions, Variables and Intrinsic Functions ....................... 76
Topic A - Naming Rules ................................................................................... 76
Topic B - Understanding Expressions and Statements .................................... 78
Topic C - Declaring Variables .......................................................................... 81
Topic D - Understanding Data Types ............................................................... 85
Topic E - Determining the Value of Variables .................................................. 89
Topic F - Using Built-in VBA Functions ............................................................ 92
Topic G - Understanding Constants ................................................................. 98
Topic H - Using Message Boxes .................................................................... 100
Topic I - Controlling the Answer to a Message Box ....................................... 104
Topic J - Using Input Boxes ........................................................................... 107
Topic K - Declaring and Using Object Variables ............................................ 111
Module 5 - Controlling Program Execution ........................................................ 114
Topic A - Understanding Control-of-Flow Structures...................................... 114
Topic B - Using the If...End If Decision Structures ......................................... 116
Topic C - Nested If Statements ...................................................................... 117
Topic D - Using the Select Case ... End Select Structure .............................. 123
Topic E - Using the Do ... Loop Structure ...................................................... 125
Topic F - Using the For ... Next Structure ...................................................... 128
Topic G - Using the For Each ... Next Structure ............................................. 130

Page ii
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic H - Guidelines for Use of Control-of-Flow Structures ........................... 132


Module 6 - Working with Forms and Controls ................................................... 135
Topic A - Understanding UserForms ............................................................. 135
Topic B - Creating a Form ............................................................................. 135
Topic C - Displaying and Removing a Form .................................................. 138
Topic D - Aligning and Sizing Controls .......................................................... 139
Topic E - Using the Toolbox .......................................................................... 140
Topic F - Working with a Form‟s Properties, Methods and Events ................ 144
Topic G - Working with Form and Control Properties, Methods and Events .. 146
Topic H - Setting the Tab Order ..................................................................... 153
Topic I - Populating a Control ........................................................................ 155
Module 7 - Debugging and Handling Errors ...................................................... 159
Topic A - Understanding Errors ..................................................................... 160
Topic B - Using Debugging Tools .................................................................. 162
Topic C - Setting Breakpoints and Using Break Mode ................................... 164
Topic D - Stepping Through Code ................................................................. 165
Topic E - Trapping Errors with the On Error Statement ................................. 168
Topic F - Understanding the Err Object ......................................................... 168
Topic G - Working with Inline Error Handling ................................................. 169
Topic H - Writing an Error-Handling Routine ................................................. 170

List of Figures

Figure 1 - The Record Macro dialog box ............................................................... 5


Figure 2 - Macro Warning Dialog Box ................................................................. 11
Figure 3 - Save As Warning Message ................................................................ 12
Figure 4 - Save As Type ..................................................................................... 12
Figure 5 - Record Macro dialog box .................................................................... 14
Figure 6 - Quick Access Toolbar drop-down to customise the QAT.................... 15
Figure 7 - Customize the Quick Access Toolbar dialog box ................................ 16

Page iii
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Figure 8 - Modify Button dialog box ..................................................................... 17


Figure 9 - Insert Controls command .................................................................... 18
Figure 10 - VBE Environment .............................................................................. 22
Figure 11 - VBE Toolbars .................................................................................... 24
Figure 12 - Options dialog box ............................................................................ 25
Figure 13 - Help dialog box in VBE ..................................................................... 28
Figure 14 - The Help Search Option ................................................................... 28
Figure 15 - Part of the Excel Object Model Map .................................................. 29
Figure 16 - Object Browser ................................................................................. 59
Figure 17 - Icons within the Object Browser ........................................................ 60
Figure 18 - Workbook event procedure ............................................................... 71
Figure 19 - Variable scope .................................................................................. 90
Figure 20 - Sample message box ..................................................................... 101
Figure 21 - Sample MsgBox arguments ............................................................ 103
Figure 22 - Sample input box ............................................................................ 108
Figure 23 - Program flow examples .................................................................. 115
Figure 24 - User form ........................................................................................ 136
Figure 25 - Aligning dialog box .......................................................................... 139
Figure 26 - The toolbox toolbar ......................................................................... 140
Figure 27 - Tab Order dialog box ...................................................................... 153
Figure 28 - Project misunderstanding cartoon ................................................... 160
Figure 29 - Debug Error Dialog Box .................................................................. 165

Page iv
Introduction to VBA – Office 2010 QAVBA10INT v1.3

How to use this workbook


ACTIVITY USEFUL TOOL
Alongside this icon you will This icon indicates a
find details of the group / technique that will help you
individual activity or a point put what you learn into
for everyone to discuss. practice.

IMPORTANT IDEA OR HELPFUL HINT


CONCEPT
This icon guides you to tips
Generally this icon is used or hints that will help you
to draw your attention to avoid the standard pitfalls
ideas that you need to that await the unwary
understand by this point in practitioner or to show you
the course. Let your trainer how you might increase
know if you do not your effectiveness or
understand or see the efficiency in practising what
relevance of this idea or you have learned.
concept.
KEY POINT REFERENCE MATERIAL
This icon is used to indicate When we have only touched
something that practitioners briefly on a topic this icon
in this field should know. It is highlights where to look for
likely to be one of the major additional information on the
things to remember from the subject. It may also be used
course, so check you do to draw your attention to
understand these key International or National
points. Standards or Web
addresses that have
interesting collections of
information.

DEFINITION WARNING
Where a word with a very This icon is used to point out
specific definition (or one important information that
that could be described as may affect you and your use
jargon) is introduced this will of the product or service in
highlight that a definition is question.
provided. (These words will
also be found in the
Glossary at the back of the
workbook.)

Page v
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Introduction and Welcome


This course is designed to follow on from QA advanced Office application training
such as Excel 2010 Level 3 or Access 2010 Levels 3 or 4. This course although
titled Introduction to Office 2010 VBA will concentrate mostly around the Excel
2010 application model.

Macros and basic VBA are covered on the above courses, this manual/course
will take the concepts from those courses and expand beyond the use of just
record and run a macro. It will also introduce you to the Visual Basic Editor
environment in order to allow you to edit or even type you own macros straight
into the Visual Basic Editor environment.

Page 1
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Module 1 - Getting Started


This Module introduces the core concepts of macros, by discussing recording,
running, saving and editing.
By the end of this module you will have covered:
 Introducing Visual Basic for Applications
 Recording a Macro
 Running a Macro
 Absolute or Relative Cell Referencing
 Saving and Opening Files with Macros
 Adding Macros to Keyboard Shortcuts, QAT and Buttons
 Editing a Macro in the Visual Basic Editor
 Understanding the Development Environment
 Customising the Editor
 Tips for General Typing in VBA
 Using Visual Basic Help

Topic A - Introducing Visual Basic for Applications

What is VBA?
Office 2010 provides Visual Basic for Applications as the common programming
language for all Office applications. A development environment called the Visual
Basic Editor is a fully featured built-in application for creating custom solutions
writing VBA code.

VBA is also licensed by independent software vendors (Autodesk is one


example), so you only need to know one programming language to write code for
other applications.

Page 2
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Reusable Components
The same functionality provided to the Office 2010 end-users is available to the
developer through the set of object interfaces. Objects are reusable application
components that you can control programmatically and incorporate into your
custom solution. For example, to display a chart in your custom solution, you can
use the CHART object provided by Microsoft Excel.

When designing a more custom solution, you can control objects from within one
Office application and work with objects provided by other applications. That
makes it easy for the end-users to work with features and functionality of Office
2010 without having to know which application they‟re working with. That is
beyond the scope of this manual.

VBA is known as an object-orientated language. Excel has a large collection of


objects available for the developer to control.

Why Use Macros?


 Automate repeated tasks

 If end-users need to carry out repeated actions efficiently and


predictably, these can be automated by recording or manually
creating a macro.
 Simplify complex tasks

 If the task to be carried out is complex, involving many steps and


therefore exposed to an increased risk of errors, the tasks can be
simplified by writing a series of macros to perform it. Within the
macros a developer can write code to help with unforeseen
circumstances.
 Build application-based applications

 You can create Wizards that sit on top of applications to help end-
users with less knowledge of that application.
 Integrate software packages

 The Office applications provide the ability for one program to control
the running of the others, which makes VBA a major tool in creating
integrated systems.

Page 3
QAVBA10INT v1.3 Introduction to VBA – Office 2010

The last two points are outside the scope of this course, however they
demonstrate what is potentially possible to experienced developers.

The Developer Tab


Available in Office 2010 is an extra tab containing many advanced icons available
to use within an application. In Excel from the right-click on the ribbon, select
Customize Ribbon, on the right side of options, check the option to show the
Developer Tab in the Ribbon.

If you do not show the Developer Tab, there are Macro related icons on the View
Tab. However the Developer Tab has more options within the ribbon that relate
to macros and VBA.

This manual will show instructions throughout that make use of the Developer Tab. If
you display the Developer Tab in one Office 2010 Application, it will appear in others
automatically.

Topic B - Recording a Macro

Why Use the Recorder?


Macro Recorder is considered to be a useful tool in creating VBA script. For
simple task automation routines you may not need to do anything to the program
once it has been created by recording a 'dry run', but the normal procedure is to
record the steps, then tidy and amend the program code by hand.
The advantages of using the recorder:
 Speed of programming
 Opacity of the language
 Create code relating to a large number of objects
 Good learning medium
Beginners will find their speed of program creation considerably enhanced by
utilising the recorder, because it looks after the „housekeeping‟ of the program
structure and saves you having to refer continually to the programming manuals.
The Macro Recorder often adds additional code when recording to make the
code more robust.

Page 4
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Starting the Recorder


The basic operation of recording a macro is fairly straightforward.

1. Decide on what the macro is to do, and how much you can record. Always
consider how you are starting and finishing the macro.

2. Select the Developer tab, Code group and Record Macro command. A
dialog box appears (see Figure 1, below) which allows you to supply a name
for the macro. It is usually a good policy to think of meaningful names which
should be distinct within a file.

3. Choose to save the macro in the current workbook or in a file where it can be
accessed by all spreadsheets in Excel. In Excel it is in the Personal Macro
Workbook, and once saved all macros within will be available to every file.

The Personal Macro Workbook is stored within the local C: Drive of your computer, it
is saved within a folder called XLSTART. When Excel starts, a file called
Personal.XLSB is loaded. Word has a similar master file for macros, this is called the
Normal Template and is called Normal.dotm.

4. The dialog box also allows you to type comments about the macro, like the
purpose of the macro. These lines are entered as program comments at the
start of the routine.
5. Press the OK button and the recording begins.

Figure 1 - The Record Macro dialog box

Everything that you now do will be recorded – including clicking on icons,


keyboard operations or re-sizing the display.

Page 5
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Items you type into dialog boxes or into the document are not recorded until the
completion of the operation, however the macro recorder often over compensates
and may record settings not altered within a dialog box.

Stopping the Recorder


Stopping a Recorder can be done in a couple of ways:

 On the status bar (at the bottom of your screen) click on the stop icon .
 Select the Developer Tab, Code group and Stop Recording command.

You may find yourself recording well past the intended duration of the macro. If you
fail to stop recording, Excel does not know this. You will record every action taken
and if not careful cause Excel to crash.

VBA automatically uses a module when recording to store the procedures in. For
the first recording made in a session of use, a new module is always generated.

Code can be moved between modules freely to give sensible grouping of routines
within your modules. Module management is covered in more details later.

The automatically created module, when recording a macro is Module and stored
within the VBA environment. There are no limits to the number of modules, but like
Sheets in a workbook, it is sensible to manage them with good naming conventions
and also remove empty modules.

Topic C - Running a Macro


There are a many ways of running a Macro:

 Click on the Developer tab; select Macros from the Code group. From the list
of macros choose the one you want to run and click on the Run button.

 Use a keyboard shortcut that has been assigned when the macro was
recorded.
 Click on a command on a Quick Access Toolbar.
 Click on a button that has a macro assigned to it.

Page 6
Introduction to VBA – Office 2010 QAVBA10INT v1.3

The decision on how to enable the end-user to run your macro depends on the
nature of the application, the contexts in which the procedure can sensibly be
used and the „look and feel‟ which will best suit the end-user.

The Developer, Macros, Run and shortcut keys are not very user friendly, and
are most likely to be used only during development by the developer to allow
quicker access.

The use of the Quick Access Toolbar is appropriate if the macro can sensibly be
run from a variety of contexts within the application.

Attaching a procedure to a button is appropriate if the procedure can only


sensibly be run when the button is visible to the end-user on a specific sheet/area
of a sheet.

To see the list of available macros, instead of going to Developer tab and selecting
Macros from the Code group, you can use a keyboard shortcut {ALT} + [F8]

Notes

www.qa.com

Page 7
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Basic Recording and Running of a Macro

Scenario
You have decided to record a basic macro for formatting numbers the way you
want.

Exercise
1. Open the file called Investors.xlsm.

2. Select some cells (not all of them) which contain numbers in Column C (1 st
Qtr)

3. Left-click the Developer Tab, left-click on Record Macro located within the
Code group of icons.

4. Alter the Macro Name to FormatCurrency, do not assign a keyboard shortcut,


store it in This Workbook, and add an appropriate comment if desired.
5. Left-Click OK.

6. Left-click on the Home Tab and within the Number icon group, left click on the
drop-down for Number Format (currently showing General).
7. Select Currency and then left-click on the Decrease Decimals icon twice.
8. Stop recording, use either the Developer tab or the Status Bar icon.
9. Save your file.

10. Select some unformatted cells within the table of numbers. (do not select all of
them)

11. Left-click on the Developer Tab, left-click on Macros and select Run for the
FormatCurrency macro.
12. Save and Close your file.

Review Question: You are in the finance industry and use a format for negative
numbers in red and brackets. Where can you store a Macro so it would be
available for every Excel file you open?

Page 8
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic D - Absolute or Relative Cell Referencing


In exactly the same way as you need to consider the use of absolute and relative
addressing when you construct formulae on worksheets, you need to be aware of
the effects of recording Visual Basic code in absolute or relative mode.

To toggle between Absolute and Relative mode use the Use Relative
References command this can be found on Developer tab within the Code
group.

If you work in Absolute mode, the addresses of cells you select will be noted
„absolutely‟, i.e. the replay of the code will affect the cells which were affected
during recording.
Range("B3").Select
Selection.Font.ColorIndex = 3
Often, though, you wish the macro to be run on any cell which bears some
definable relationship to the starting cell (e.g. the cell below). In this case, it is
best to switch the recorder to work in Relative mode, which causes it to use a
different set of commands and thus to indicate that the position of the chosen
cells is dependent upon the start location.
ActiveCell.Offset(1,0).Range("A1").Select
Selection.Font.ColorIndex = 3
In both code examples above, we started in cell B2, selected the cell below, and
set the colour to red. The first example uses Absolute references, and always
selects cell B3 to be formatted, regardless of the starting position of the cursor on
replay. The second example uses Relative references, and always selects the
cell below the starting position of the cursor.

Page 9
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Working with Relative or Absolute Cell References

Scenario
In this scenario you are going to record a Macro that will transfer data from a
Monthly sheet and append the data to a Yearly (all data) sheet. Jan-Mar has
already been completed prior to a decision to try and use a macro to speed up
the process. First we will practice, then we will Record the steps below.

Exercise
1. Open the file called All Data.xlsm. Note that Jan to Mar are empty as their
data is already in the All Data sheet.

2. Practice the routine first on the Apr sheet, then Record the steps shown below
on the May sheet.
3. Delete row 1. Left-click in A1 only. Press {CTRL} + [*].
4. Use your preferred method for Cut.
5. Select the sheet called All Data.
6. Press {CTRL} + [Home], then press {CTRL} + [Arrow Down].
7. On the Developer Tab, left-click on Use Relative References.
8. Press [Arrow Down].
9. Use your preferred method for Paste.
10. On the Developer Tab, left-click on Use Relative References.
11. If you are recording then Stop recording, and Save the file.
12. Start with the May sheet displayed.

13. Record a macro called AddMonthlyData, use the Keyboard Shortcut option,
type {SHIFT} + [A] in the option. Repeat steps 3-11 on the May sheet.
14. Test the Macro with your keyboard command on sheets Jun through to Dec.
15. Close the file when finished testing and Save changes.

Review Question: Discuss the following. What could make this macro go
wrong?

Page 10
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic E - Saving and Opening Files with Macros

Opening a File with Macros


When you open either an XLS (that contains Macros/VBA) or an XLSM/XLSB you
will be prompted to enable the contents of the file so the macros can be utilised.
Code can contain malicious VBA intended to do harm (like a virus) and, if you are
unsure of your files source, always disable the content. Then seek assistance or
manually check the VB Editor for code to see if there are any signs of malicious
commands.
You will be shown a strip above the spreadsheet (see below) asking for the
content to be enabled when opening XLSM files for instance.

Figure 2 - Macro Warning Dialog Box

You will then have a dialog box confirming the enabling of your macros.

This warning may differ if your file is in Compatibility Mode (or other reasons).
Instead of the security bar you will have a dialog box. Buttons to Enable or Disable
will be available.

Saving a File
When you save an Excel file, Office 2010 requires the file extension normally
XLSX to be XLSM (XLSB in some cases). This informs a user that there are
Macros within a file even before opening it.
 XLSX – A standard Excel 2007/2010 file, no VBA (in XML compiled format)
 XLSM – An Excel 2007/2010 file containing macros/VBA
 XLSB – An Excel 2007/2010 binary formatted file containing macros/VBA

 XLS – An Excel 2003 compatible file format that may or may not contain
macros/VBA.

If you are working in the VB Editor, Save is available in standard methods such as
the File menu, or the Save icon, and this will save the Excel file that contains the
code.

Page 11
QAVBA10INT v1.3 Introduction to VBA – Office 2010

When working within an XLSX file, and initially developing code, when you go to
save the file for the first time with code inside, Excel will warn you to save the file
in an alternative file format.

As shown n the figure below, No will then display „Save As‟, enabling you to
choose save as a Macro-Enabled Workbook (as shown in Figure 4).

Figure 3 - Save As Warning Message

Figure 4 - Save As Type

Notes

www.qa.com

Page 12
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Opening and Saving your Macro Enabled Workbook

Scenario
This is to show how Excel can protect you against a potential harmful macro, also
if you are working with and XLSX file and you try to save with a Macro inside the
warnings to alter the file type to XLSM.
Before you start, close any open files in Excel.

Exercise
1. Open the file called Investors.xlsm. (Worked on previously)
2. Note the warning strip over the top of the screen, left-click on Options
3. Left-click on Enable this content.

4. Run the currency formatting macro on a selection of cells that may still not be
formatted.
5. Save and Close the file..
6. Open the file called Company Results.xlsx.
7. Select cells A12 to D12 (The total area)
8. Record a macro called AddBorders

9. From the Home tab, Font icon group, use the Borders icon and select a
border of choice. e.g. Top and Thick Bottom Border
10. Stop recording.
11. Left-click on Save, note the warning message.
12. Select the No option.
13. From Save as type select a Excel Macro-Enabled Workbook.
14. Close the file.

Review Question: What do you think Word will do to a file called DOCX if there
is a macro saved within it?

Page 13
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic F - Adding Macros to Keyboard Shortcuts, QAT and


Buttons

Keyboard Shortcuts
One way to run your macro manually is to nominate a shortcut within the recorder
start-up dialog box, as shown here.

Figure 5 - Record Macro dialog box

If you use a keyboard shortcut note these potential issues.


 The keyboard shortcut is case sensitive
 Many keyboard commands already exist, you can overwrite them

 You cannot remove the use of {CTRL} but can add {SHIFT} to help with
keyboard combinations
 Shortcut keys can also be difficult to remember

If you assign a procedure to {CTRL} + [C] you will disable the use of Copy whilst the
file containing the keyboard command is open (Excel). This applies to all other
keyboard commands. In Word you will see the command assigned to a keyboard
command, e.g. EditCopy.

Page 14
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Quick Access Toolbar


One convenient way to run a macro from any Office 2010 application is to add a
macro command to Quick Access Toolbar (QAT).

Figure 6 - Quick Access Toolbar drop-down to customise the QAT

The QAT displayed above shows the drop-down arrow where you can locate and
add additional commands to the QAT, to add a command follow this process:

1. Left-click on the down arrow at the end of the QAT and select More
Commands…,
or
Left-click File Menu, then select Options and finally select the category
Quick Access Toolbar.

The dialog box will be displayed on the screen.

Page 15
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Figure 7 - Customize the Quick Access Toolbar dialog box

2. From the Choose command from: list, select Macros.


3. Left-click on the macro that you want to add to the QAT.

4. Left-click on Add >> button.


The macro will be copied to the QAT.
5. Select the macro from the list on right side of the dialog box.

6. Left-click Modify… button.


The dialog box will be displayed on the screen (see Figure 8)
7. Select the icon you want to use.

8. In the Display Name text box, type a text that you want to appear as a tool-tip
when you place a mouse cursor over the command (see example on Error!
eference source not found.)
9. Left-click on OK button.
A new command will appear on the Quick Access Toolbar and when left-clicked
will run the code assigned to it.

Page 16
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Figure 8 - Modify Button dialog box

In the upper right area of Figure 7 is an option that allows the QAT to be customised
further. When the file containing a procedure is open you can automatically add an
icon to the QAT, and then have it removed when you close the file.

Buttons
To insert a button, you must select an Insert command from the Controls group
on the Developer tab.

Reminder, Once the Developer tab is active, it will be automatically be available in


other Office 2010 applications.

There are two types of buttons that you can put onto a worksheet to run a macro.
These notes cover the simpler of the two, a Button (Form Control) option that is
available from the Form Controls section, within the Controls icon group.

In Figure 9 - Insert Controls command. There are also a group of icons called
ActiveX controls, the Command Button icon behaves different to the Button
icon within Forms. Code is placed directly behind the button.

Page 17
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Figure 9 - Insert Controls command

To place the button on the worksheet, left-click the button icon within the
Controls icon group so that it looks pushed in. Then left-click within your
spreadsheet to generate a default size button.

In Excel, if you hold the {ALT} key down while resizing or moving the button it will
snap to the worksheet grid, making the layout look neater

When you release the mouse button the Assign Macro dialog box will be
displayed. If you have already created the macro for this button, select its name
and left-click the OK button.

If you have not created a macro, but still add a button, you can record the macro
now by clicking the Record… button, or you can Cancel this dialog box, then
write or record the procedure and go back and assign it to the button by right-
clicking the button and selecting the Assign Macro… command.
It is a good idea to change the button's caption before going further. Right-click
the button, select Edit Text and then edit the caption on the button. Note the tip
above to resize a button and align within Excels gridlines.

To then use the button to run a macro, left-click away from the button, this will
deactivate its borders. Left-click on a button will now run the macro procedure
immediately. Right-click on a button will allow you to manage the button‟s
settings.

Page 18
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Adding Macros to the Quick Access Toolbar and to Buttons on


a sheet

Scenario
This activity will take you through the process of adding a macro to the Quick
Access Toolbar and also to buttons. We will also start to look at using Word, and
how similar the processes are.
As a lottery syndicate manager you are fed up with entering the date on the form
each time a syndicate changes, you have created a macro to find and replace the
word NOW with today's date.

Exercise
Adding a Macro to the Quick Access Toolbar
Before we start, open the Agreement.docm file and enable macros.
Note the locations of the word NOW which the Macro will convert to today's date
for us.
1. Open the Customize the Quick Access Toolbar dialog box.
2. In the Choose commands from: drop-down list select Macros.
3. Alter the Customize Quick Access Toolbar to For Agreement.
4. Select macro AlterDate and then Add>> it to the current icons.
5. Left-click on Modify, and alter the Name and Icon as you wish.
6. Close the Customize the Quick Access Toolbar dialog box.
7. Test your macro by left-clicking on it from the button on the QAT.
8. Note the words NOW alters to today's date.
9. Save and Close the file. (The icon should disappear from the QAT.)

Adding a Macro to a Button


Before we start, open Investors.xlsm file and enable macros.

1. On the Developer tab, from the Controls icon group, left-click on Insert and
then left-click the Button from the Forms Controls area.
2. Single left-click in a blank area of the spreadsheet.

Page 19
QAVBA10INT v1.3 Introduction to VBA – Office 2010

3. Assign macro FormatCurrency to the button.


4. Right-click and select Edit Text on the button. Change the text to Currency.

5. Test your macro on some unformatted cells by left-clicking on the newly


created button.
6. Save and Close your file.

Notes

www.qa.com

Page 20
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic G - Editing a Macro in the Visual Basic Editor

Starting the Visual Basic Editor


The VBA editor is displayed in a separate application window. You can left-click
on the Developer tab and select Visual Basic from the Code group. A
convenient way to open the editor is the keyboard shortcut combination {ALT} +
[F11].

Visual Basic code is stored in Modules within the current file, and you can use
Insert, Module to create a module manually if you desire.

Organisation of Visual Basic Code


Within a module, you can place any number of Procedures (usually a Sub or a
Function). Each procedure can perform a single task, multiple tasks or can call
others procedure within any module. Segregation of procedures into different
modules is done only for your convenience, however each time you record a
macro within a file a new module maybe created automatically.
Each module has a pre-defined structure:

 At the top are options known as general declarations – warning the compiler
about variables and constants (covered later) which are to be used throughout
the module. This in essence makes the „rules‟ for the entire module.

 Then each procedure has a section of its own starting with Sub or Function
and finishing with a matching End Sub or End Function. (known in VBA as a
Page)

If you print a module, the line separator between procedures will not print.

Closing the VB Editor


When you are finished using Visual Basic Editor (VBE), you can either close or
minimise the VBE window.
This can be done by:

 Clicking on an icon in the top right of the window

Page 21
QAVBA10INT v1.3 Introduction to VBA – Office 2010

 Open the File menu and select the Close and Return to Microsoft
Application command
 Using keyboard shortcut {ALT} + [Q]

The VB Editor cannot run without the host Office Application, so even if you didn‟t
close VB Editor before you returned to the application, VB Editor will be
automatically closed when you close your application.

Topic H - Understanding the Development Environment

The Visual Basic Editor

Figure 10 - VBE Environment

The editing environment is the same in all of the VBA-equipped programs (Excel,
Word, etc.) and very similar to that of Visual Basic.
The Editor by default is made up of three windows.
 Project Explorer (top left)

Page 22
Introduction to VBA – Office 2010 QAVBA10INT v1.3

 Properties (bottom left)


 Code (main window on right)

There are others windows available, which are not shown here. Some will be
discussed later within this manual. You will need to become familiar with the roles
of the different windows, and with arranging the screen so that the information
you need is clearly visible.

Project Explorer Window


This window shows three key areas for code storage: Modules, where macro
procedures are stored after recording or editing; Microsoft Office Objects, code
can live behind a sheet/file object or within the actual file, this is often used for
event driven procedures; Forms (not shown in Figure 10 - VBE Environment) will
be listed within the Project Explorer if created, see Module 6 for Forms).

If the Project Explorer is not visible, left-click on the Project Explorer icon on your
toolbar ( ), or press {CTRL} + [R].

Properties Window
This window will allow you to rename a Module (if selected from the Project
Explorer window). The use of the Properties window is minimal when working in a
code window, but, when working with forms, or Excel objects, it will have more
options available.

If the Properties Window is also not visible, left-click on the Properties icon on the
standard toolbar ( ) , or press [F4].

Code Window
The code window will show VBA script either manually created by a developer, or
code created when macros are recorded. The first line of a procedure will start
with either Sub or Function, and, this is the only place where a macro/function
can be renamed.

If the code window is not displayed double-click on a module or object within the
Project Explorer window, or press [F7].

Page 23
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Toolbars
The most used buttons from the Standard and Edit VBE toolbars are displayed
in Figure 11. The Run (Press [F5]) and Reset icons are equivalent to run a macro
and stop running, if your cursor is within a procedure in the code window, it can
be run from the VB Editor.

Figure 11 - VBE Toolbars

The Edit toolbar (shown above) is not displayed by default. Right-click on the
Standard toolbar and select Edit.

Topic I - Customising the Editor


The Tools, Options command opens a dialog box that holds settings to manage
how the VB Editor behaves. There are too many options to discuss here,
however some useful settings to be considered are discussed.

The Editor tab has useful check boxes which control the editor. For legibility it is
important to develop the habit of indenting blocks of code, and the Auto Indent
check box causes the cursor to jump to align with the start of the preceding line
rather than the first column.

Page 24
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Figure 12 - Options dialog box

The word Syntax means a defined set of rules for the programming language,
within VBA learning syntax is all part of a developers learning curve. Throughout
this manual, syntax is shown to demonstrate the rules of a set of code. If your
code is syntactically incorrect a standard message box warning you and the
colour red is used. If you switch off Auto Syntax Check any lines of code with
bad syntax in them will still turn red, no warning message will be displayed.

Developers often use copy and paste or move between lines of code before lines of
code are complete. This often produces a Syntax error. Just seeing red is often
enough warning.

If any code remains in red in any module, the whole VBA environment will not work.
You must resolve red lines of code before attempting to run any macros.

The Require Variable Declaration option is also helpful in preventing errors. It


results in the line Option Explicit being entered automatically at the top of each
module.

The Editor Format tab determines the font and colour scheme used for
displaying code within modules.

Page 25
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Normally comments to appear in green, syntax errors in red, VBA keywords in


navy blue and so on. You may prefer to change the comments or keyword colour
to something more easily distinguished from black (e.g. a different blue), but, as
in all discussions of colour, you need to be aware of any colour-blindness in
colleagues and to choose the colours appropriately!

VBA does not print in colour, there are free text editors available online that will
when code is pasted into it. For instance SciTE

The General tab contains a variety of settings, many are beyond the scope of
this manual. The Docking tab determines which windows will automatically dock
to the edge of the VBE window.

Topic J - Tips for General Typing in VBA

Code Window
The VB Editor is equipped with a useful monitoring tool which watches as you
type. Microsoft call this „Intellisense’, it can save much of the typing and prevent
spelling mistakes in your code since it provides you with the available options.
It springs into action on following occasions:
 as you type a dot [.] after a recognised object
 as you type an open bracket [(] after a function
 as you type a space [Space] after a method

You can also force Intellisense to work by using {CTRL} + [Space].

When there are more options starting with the characters you‟ve typed, you will
be offered a list to choose from. The selection from the list can be completed by
pressing a [TAB] key, or clicking with your mouse, or by using the various
keyboard commands mentioned in the list above if that is the next character. The
[ENTER] key can be used too, but it will also create a new line in the code which
might not be what you want.

Page 26
Introduction to VBA – Office 2010 QAVBA10INT v1.3

VBA also offers 'QuickInfo' as often syntax requires you to complete line of code
with various options. QuickInfo is displayed below you cursor as you type
showing which area of a code statement you are in.

Many of the features mentioned here are availbale on the Edit toolbar in the VBE.
They are also on the right-click menu.

Browsing through VBA Code


Scroll through VBA code with your mouse, or use the arrow keys on the
keyboard.

Shortcut Action

{CTRL} + [Up Arrow]/[Pg Up] Moves to previous procedure

{CTRL} + [Down Arrow]/[Pg Dn] Moves to next procedure

{CTRL} + [Home]/[End] Moves to the beginning / end of a module

{CTRL} + [F] Find

[F3] Find again (without the „Find‟ dialog box open)

Topic K - Using Visual Basic Help

Context-Sensitive Help
If you need help on understanding existing code, place the cursor in a keyword
and press [F1]. Examples are often included within help pages and can be very
useful. They will normally appear at the bottom of the help descriptions and they
can be copied, pasted and then altered within your code.

General Help
You can get help by pressing [F1], or using Help, Microsoft Visual Basic Help
from the menu. In the dialog box that appears, you can either type in the Search
box or Browse the help topic that appears on the list (see Figure 13 below).

Page 27
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Figure 13 - Help dialog box in VBE

Within the VB Editor there is a help box in the upper right corner of the screen
where developers can enter search words.

Figure 14 - The Help Search Option

The Object Model


VBA Applications have an object model reference which lists all of the objects
that you can use in VBA for the application you are using. Excel has well over
200 objects. The figure below shows that there are many objects, and also
collections of objects within each application (In this example Excel).

Page 28
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Figure 15 - Part of the Excel Object Model Map

Notes

www.qa.com

Page 29
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity - Working in the VB Editor Environment

Scenario
This activity will allow you to understand concepts available within the VB Editor.
You will rename a Module, and a Macro. You will enter lines of Code, both as
comments and actual actions. You will see intellisense in operation, and finally
drop into help.

Exercise
Before we start, open the Travel Expenses.xlsm file and enable macros.
1. Press {ALT} + [F8] and left-click on Edit for the FormatHeadings macro.
2. Left-click on the Module1 within the Project Explorer window.
3. In the Properties for Module1, alter the (name) property to modFormatting
4. In the Code Window, alter the name of the macro to HeadingsFormat.

5. Delete the comment that mentions the name of the macro, in its place write a
comment that contains your name and today's date.
6. Follow the comments above the blocks of code and alter where required

7. On the Editor Format tab, select the Keyword Text option and from the
Foreground options below, select the royal blue colour towards the bottom
that is above lime green.

8. Select Sub, and press [F1], observe help - note the Syntaxes you might see
within help. (In Office 2010 when you press F1, it defaults to searching the
online help from (“Show Content from Office.com”), you have to switch to
“Show content from my Computer” for this to work).
9. Repeat the use of [F1] for both Bold, and then Italic.

10. Below the help description, select the Font Object Members and observe
other members of the Font Object.
11. Close Help, Quit the VB Editor.
12. In Excel, Save and Close the file.

Page 30
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Module 1: Review

This module was about:

 Introducing Visual Basic for Applications


 Recording a Macro
 Running a Macro
 Absolute or Relative Cell Referencing
 Saving and Opening Files with Macros
 Adding Macros to Keyboard Shortcuts, QAT and Buttons
 Editing a Macro in the Visual Basic Editor
 Understanding the Development Environment
 Customising the Editor
 Tips for General Typing in VBA
 Using Visual Basic Help

Review Questions:
1. If you display the developer tab, which other Office applications also display
the Developer Tab?
2. Where is the only place you can rename a macro?
3. When you type Sub MacroName and press enter what will automatically
happen within the VB Editor?
4. What is the file extension for a PowerPoint 2010 file containing a Macro?

5. When using help, which keyboard command can take you straight to the
relevant help section?

Page 31
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Module 2 - Working with Procedures


This module explains where VBA code is stored within a file. You will write code
rather than record for both subroutines and also functions.
By the end of this module you will have covered:
 Program Design
 Understanding Modules
 Creating a Module
 Understanding Procedures
 Programming Macro Concepts
 Creating a Subroutine
 Creating a Function
 Understanding Arguments
 Exiting Procedures
 Calling Procedures

Topic A - Program Design


Planning your program is important if you anticipate the need for anything beyond
a simple task. While you may be able to visualise all of the actions which need to
be carried out, it is almost inevitable that you will have second thoughts, or your
end-users‟ reactions to the first release may dictate changes.

It is, therefore, good practice to make a specification of the application, so that


you can ensure that all aspects have been considered.
While you are considering the logic of the program, look at ways in which the
processing can be segregated into small sections – sometimes the same chunk
of code may be reused several times, so this can obviously be separated out.
This process leads to a well-structured program which is easy to write, test,
document and maintain.

It is a characteristic of applications written in VBA that they use a fairly large


number of very short blocks of code (called Procedures).

Page 32
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic B - Understanding Modules


A module is an element within the VBA hierarchy that sits in the VB Editor of a
file. It holds a set of declarations (options) followed by a number of procedures
(macros).

Each module has a unique name the naming rules are similar in other areas
within VBA, the standard prefix used for modules is mod.

Use the Properties window to alter the name of a module. In Excel, sheets are often
renamed. The (name) property is the only property available for a module.

It is good practice to group procedures in a module. For example, create a


module called modConversions that will have all the procedures that are used for
converting one unit into another. We can also have a module modDataTransfer
that will have all the procedures used for importing, altering and finally exporting
your data.

A module can be exported to a separate file, and subsequently imported into


another project (or to Visual Basic, Access, etc.). This makes modules very
flexible and reusing them makes our life much easier.

To export a module, Right-click on its name and select Export module name. This
will create a .BAS file that can be read by any text editor.

Each module has a formal structure. The top area of a module dictates options
which are to be used throughout the module this area is called General
Declarations. The area is not always used, and if blank, then a modules first code
is a procedure.

Following General Declarations are procedures, these are the macros/code


created by developers.
Option Explicit General Declarations
'This Module Formats my sheet
____________________________________________________________
__
Sub HeadingsFormat() A Procedure
Range("B3:D3").Select

Page 33
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Selection.Font.Bold = True
Range("B20:D20").Select
Selection.Font.Italic = True
Range("A1").Select
End Sub

Topic C - Creating a Module


A module is a container for procedures that can be used from anywhere in the
project, as well as from any other application that understands VBA language.
You can create a standard module in many ways:
 Open the Insert menu and select a Module command.

 Left-click down arrow next to the icon on the Standard toolbar and
select Module.

 Right-click on the project name in Project Explorer and select Insert,


Module command.

To open any module in the Code window, double-click on it in the Project window.

If you record a new macro within a file a new module maybe created
automatically. Subsequent macros are stored within the same module, each
separated by a line until you close the application.

Topic D - Understanding Procedures

Definition
A procedure is a block of program code which has been assigned a name.

VBA does not support nesting of procedures within each other, so you must finish
off one procedure and then start the next. You can, however, call one procedure
from another one.

Page 34
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Once you have a module that can be worked with, procedures can simply be
typed into the Code Window.

Types of Procedures
There are multiple types of procedures supported by VBA, but this course deals
with the two most commonly used:
 Subroutine

 A procedure that performs a specific task within a program, but


returns no value.

 A Subroutine begins with a Sub statement and ends with an End


Sub statement.
 Function

 A procedure that performs a specific task within a program and


returns a value.

 A Function procedure begins with a Function statement and ends


with an End Function statement.

Naming Procedures
The naming rules for procedures are the same as for many other VBA elements
explained elsewhere in this manual.

You can insert a procedure from the Insert menu. However most code developers
simply type into a module.

Topic E - Programming Macro Concepts

Modular Concept
By breaking up a large program into smaller units, a program can be made a lot
easier to read, and therefore a lot easier to understand and easier to fix or debug
when it goes wrong. In some cases, splitting the program up into units may
enable the programmer to spot bugs before they go into a production program. A

Page 35
QAVBA10INT v1.3 Introduction to VBA – Office 2010

program which is easy to read should also be easy to maintain. The process of
splitting a long program into manageable fragments in this way is known as
modularisation.

Another important reason for designing programs as short procedures is that


often a piece of code gets repeated at different stages in the execution of the
program. Because one procedure can „call‟ or „run‟ another, the code can be
shortened by removing the repeated sections.

Beginning, Middle, End


Most tasks can have their actions grouped into start, middle and end actions:
1. Beginning
Actions to be carried out once, at the beginning of the process.

For instance you may wish to copy data from one sheet to another. Potentially
starting on the wrong sheet, and making sure you have to select relevant data
at the beginning can ensure the macro will run smoothly each time.
2. Middle
Actions, often repeated, that form the main body of the process.

For instance you may have multiple rows or columns or data you need to
process, so separating out the middle process enables you to manage this
section of code if issues arise and not have to worry about the start of end
processes
3. End
Actions carried out once, at the end of the process.

Similar to the Start, it is often worth selecting cells even though you may think
you have finished, or pressing ESC for instance if you have been using cut or
copy.

Page 36
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic F - Creating a Subroutine

Definition
A subroutine is a procedure that performs a specific task within a program, but
returns no value.

Syntax
A Subroutine begins with a Sub statement and ends with an End Sub statement.
In between those two statements is the body of the subroutine. This maybe as
little as one line of code, or as many as you require.
Sub name [(arglist)]
[statements]
[Exit Sub]
End Sub

If you are sending values into a routine, then the brackets can be used within a
procedure. The values within a bracket are known as arguments, see notes later
on understanding arguments.

Creating a Subroutine
You can create a subroutine in various ways, depending on what you are doing,
sometimes the macro recorder may not be of use and code must be manually
typed.

Only Word and Excel have the ability to record macros. PowerPoint, Outlook and
Access must have code manually written within modules.

These are the various methods for generating procedures:


 Recording a macro from Excel (already covered in detail)
1. Left-click on the Developer tab
2. From the Code group left-click the Record Macro command
3. Type a macro name and Press [Enter] or left-click the OK button

Page 37
QAVBA10INT v1.3 Introduction to VBA – Office 2010

4. Do the steps that you want to record


5. Locate and left-click on Stop Recording

 Using menu in VB Editor (not recommended)


1. Left-click on the Insert menu
2. Select Procedure… command
3. Type a subroutine name
4. Click on the Sub option
5. Press [Enter] or click the OK button

 Manually creating a subroutine (recommended)


1. Left-click outside any existing procedures
2. Type the keyword Sub and the name of the macro
3. Press [Enter]

4. End Sub is automatically generated and you can continue within the
procedure to write code.

Developers will often use a combination of recording and manually editing routines
as the macro recorder provides you with lines of code quickly.

Page 38
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Creating a Module and Procedure

Scenario
This activity will take you through the process of creating a module and a sub
procedure within that will add relevant headings and format to a file.

Exercise
Before we start, open the Profit Calculation.xlsm file.
1. Press {ALT} + [F11], to access the VB Editor.
2. Select Insert, Module, and rename the module to modFirstProcedure
3. In the Code Window, type the following procedure.
Option Explicit
___________________________________________________
Sub AddHeadings()
Range("A1").Value = "OGC Appliances"
Range("A4:A16").Font.Bold = True
Columns("A:A").AutoFit
MsgBox "Macro Complete"
End Sub

4. In the VB Editor, Save the file.


5. From within the VB Editor, locate the Run icon and left-click it.
6. Switch back to Excel and observe the changes.
7. Return to the VB Editor.
8. Alter the word Bold to Italic, and the columns for auto fitting to A:E.
9. Restore the VB Editor window so you can see the Excel behind the VB Editor.
10. Left-click on Run from within the VB Editor, observe changes made in Excel.
11. Maximise the VB Editor window.

Page 39
QAVBA10INT v1.3 Introduction to VBA – Office 2010

12. Save the file. This file is used for the following activity, you may wish to keep it
open.

Topic G - Creating a Function

Definition
A function is a procedure that performs a specific task within a program and
returns a value.

If created within Excel, these functions will be available to end-users within the
application. In the same way other functions are written e.g. =Sum() etc. Within
Access functions will be available to Queries, Forms and Reports.

Syntax
A function procedure begins with a Function statement and ends with an End
Function statement. In between those two statements is the body of the function.
Function name [(arglist)] [As type]
[statements]
[Exit Function]
[name = expression]
End Function
The values within a bracket are known as an argument.

A Function procedure also has settings outside of the brackets which dictate the
type of value being returned by the function. See Understanding Data Types for
more information within this manual.

Within the body of a function we must include a statement that consists of the
function name followed by an = sign and then followed by a value that we want
the function to return. This is usually a line just before the End Function
statement.
Function FullName(strFName As String, strSNname As String)
As String
FullName = strFName & " " & strSName
End Function

Page 40
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Creating a Function
You can create a function by:
 Using the menu in the VB Editor (not recommended)
1. Left-click on the Insert menu
2. Select Procedure… command
3. Type a function name
4. Left-click on the Function option
5. Press [Enter] or click the OK button
 Typing the syntax yourself (recommended)
1. Left-click after the end of the last procedure in a module
2. Type a keyword Function followed by a function name
3. Press [Enter]

End Function is automatically generated and you can continue within the
procedure to write code

Notes

www.qa.com

Page 41
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity - Creating a Function Procedure

Scenario
This activity will take you through the process of creating a separate module
andfunction procedures within that to add to your spreadsheet.

Exercise
1. Before we start, confirm the Profit Calculation.xlsm file is open.
2. Press {ALT} + [F11], to access the VB Editor.
3. Select Insert, Module, and rename the module to ModFunctions
4. In the Code Window, type the following procedure.
Option Explicit
____________________________________________________________
Function CalcTax(NetIncome As Single, TaxRate As Single) As
Single
CalcTax = NetIncome * TaxRate
End Function
____________________________________________________________
Function ProfitAfterTax(Tax As Single, NetIncome As Single)
As Single
ProfitAfterTax = NetIncome - Tax
End Function
____________________________________________________________
Sub TestCalc()
MsgBox CalcTax(1000, 0.2)
End Sub

5. In the VB Editor, Save the file.


6. Left-click inside the routine TestCalc.

Page 42
Introduction to VBA – Office 2010 QAVBA10INT v1.3

7. Press the Run ([F5]) icon and confirm the message box is 20% of 1000
8. Return to Excel and select cell B14
9. Enter =CalcTax(B12,E2)
10. In cell B16 locate the fx icon above Column B.

11. Alter the Category to User Defined, and select ProfitAfterTax.


12. Click OK and select the relevant cells as required by the function.
13. Return to the VB Editor.
14. Select View, Immediate Window command from the menu.
15. In the Immediate window enter:
? CalcTax(10000,0.05)
16. Type also into the Immediate Window the following code and press enter:
MsgBox CalcTax(10000,0.05)
17. Close the Immediate Window, and return to Excel.
18. Save and Close the Excel file.

Notes

www.qa.com

Page 43
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic H - Understanding Arguments

Definition
An argument is simply a value passed into a procedure. Another term for
arguments is Parameters and they are used interchangeably. Experienced Excel
users will be used to arguments as they are used when writing functions to make
them work.

The name with which parameters will be recognised within the procedure, and
the type of data expected are specified in the argument list. This is enclosed in
parentheses on the procedure declaration line.

Naming Arguments
The naming rules for arguments are the same as for many other VBA elements
explained elsewhere in this manual

Optional Arguments
Normally the elements of an argument list are all required by the procedure. In
some cases it may be possible to manage without information from all of them.

In this circumstance you can prefix the arguments formal name with the keyword
Optional.

All required argument names must appear in the declaration before optional
arguments.

Function Day1Info(Dept As String, Optional myDOB As Date) As


Date
The declaration of an Optional argument can include a default value.
Sub ShowWeight(Weight As Single, Optional Unit As String =
"lb")
MsgBox "Weight: " & Weight & " " & Unit
End Sub

Page 44
Introduction to VBA – Office 2010 QAVBA10INT v1.3

If no explicit default is specified, a missing optional argument will result in the


following values:

Numeric types String Objects

0 “” Nothing

Activity - Using Optional within Arguments

Scenario
This activity is to test the various settings permitted within a sub/function
arguments.

Exercise
1. Before we start, create a new blank file. (Close any open files).
2. Press {ALT} + [F11], to access the VB Editor.
3. Select Insert, Module, and rename the module to modFunctions

4. Type the following code enter either the male/female section in TestOptional
and substitute 'your forename' with your name – inside quotes:
Option Explicit
____________________________________________________________
Function Fullname(Forename As String, Surname As String,
Optional Title As String = "Mr") As String
Fullname = Title & " " & Forename & " " & Surname
End Function
____________________________________________________________
Sub TestOptional()
' if male type this:
ActiveCell.Value = Fullname("your forename", "your surname")
' if female type this:

Page 45
QAVBA10INT v1.3 Introduction to VBA – Office 2010

ActiveCell.Value = Fullname("your forename", "your surname",


"your title")
End Sub

5. Save the file (Macro-enabled) as Function Optional.xlsm, return to Excel.


6. Run the macro (TestOptional) from Excel.
7. If possible check a delegate of the opposite sex, or ask your instructor to
demonstrate both routines.
8. Save and Close the file.

Topic I - Exiting Procedures


If you need to jump out of a procedure before all of the code has been executed,
you can employ the appropriate Exit Sub or Exit Function command.
If intHoursWorked > 40 Then
MsgBox "The hours worked figure is too high!"
Exit Sub
End If
' More Code can be here
In the following example of code, a message box asks the user a question, and if
the user were to click on the No button the routine would quit.
If MsgBox(“Continue with Macro?”,vbYesNo)=vbNo Then Exit Sub

The use of IF is explained later in this manual for now read the code above, to
understand why Exit Sub was used.

Page 46
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic J - Calling Procedures


A standard way of working in VBA is to create small subroutines that run a block
of procedures and not to have a large subroutine doing too many different things.
In order to link small procedures together VBA can run one procedure after
another by 'calling' them in order.

Having defined a subroutine, you can call it from anywhere in the module using
the Call statement followed by the name of the subroutine.
Sub WelcomeMessage()
MsgBox "Welcome to York!"
Call Answer
MsgBox "Enjoy London!"
End Sub
__________________________________________________

Sub Answer()
MsgBox "We're in London now!"
End Sub
Assuming that program execution begins in WelcomeMessage, the sequence of
messages that will appear on the screen will be:
 Welcome to York!
 We‟re in London now!

 Enjoy London!

It‟s worthwhile to look at how this works in a little more detail.

1. The Call statement remembers the current position and jumps to the start of
the subroutine specified after the keyword Call.
2. The statements from that subroutine are executed in sequence.

3. At the end of the subroutine, control returns to the original procedure to the
statement just after the Call.
4. The statements of the first procedure are then executed in sequence.

Page 47
QAVBA10INT v1.3 Introduction to VBA – Office 2010

The use of {SHIFT} + [F2] and {CTRL} + {SHIFT} + [F2] will allow you to jump to and
fro within your calling procedure, even if the called procedure is within a different
module.
You can also Right-click on the named procedure and select Definition and then
within the called procedure, right-click and Last Position to return back.

A subroutine can be called from different parts of a program and will always know
how to „get back‟ at the end of the called subroutine.

If you use the keyword Call and want to send arguments, then the syntax should be
something like:

Call MySub(arg1, arg2)

Notes

www.qa.com

Page 48
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Calling or Exiting Procedures

Scenario
This activity is to test if it will be possible to exit a routine through code, and to
call other procedures as required.

Exercise
Before we start, open the Departmental Data.xlsm file and enable the macros.
1. Press {ALT} + [F11], to access the VB Editor.
2. Note the Code already exists. Have a read through each procedure.
3. The comments are there to help you.
4. Return to Excel, select cell G5, and then locate and run the AddFullName.
5. Continue testing AddFullName. Use Repeat ( [F4] ) to run this on subsequent
cells.

6. Note what happens when running AddFullName if an employee number is


above 50.
7. Remove any names generated in column G.
8. Now run AddFullName2 through column G and note the difference.

9. Return to VB Editor and within this procedure, press [F8] repeatedly, note how
VBA allows you to step through one line of code at a time.
10. Once the procedure is complete, Save the file.
11. Close the file.
Review Question: Why did AddFullName2 still produce the result even though
there was an occasional error message?

Discuss ONLY what could be done so the error is displayed


and a name is not displayed.

Page 49
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Module 2: Review
This module was about:
 Program Design
 Understanding Modules
 Creating a Module
 Understanding Procedures
 Programming Macro Concepts
 Creating a Subroutine
 Creating a Function
 Understanding Arguments
 Exiting Procedures
 Calling Procedures

Review Questions:
1. How many modules/procedures can you have within the VBA environment?

2. Which area of your module do the words Option Explicit appear?

3. What is wrong with this line of code?


Function myAge (Optional DOB As Date, AgeNow As Byte) As Byte
4. Can you place multiple Call statements together within a module?
5. What code will stop a macro immediately?

Page 50
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Module 3 - Understanding Objects, Properties,


Methods, and Events
This module will help you understand the various elements with VBA for working
with an applications objects. You will also see how to trigger VBA code to run
automatically.
By the end of this module you will have covered:
 Understanding Objects Properties, Methods and Events
 Navigating the Object Hierarchy
 Understanding Collections
 Using the Object Browser
 Using the With Statement
 Working with Properties
 Working with Methods
 Creating an Event Procedure

Topic A - Understanding Objects Properties, Methods and


Events
An Object is an element of an application that can be accessed and manipulated
programmatically.

Objects have a list of Properties and Methods that define them, and they are
able to respond to various Events. Excel and Access have a very large collection
of objects.
A collection is simply a group of similar objects.

Properties are characteristics of an object and the data values assign to them
define an instance of an object. E.g. colour of the font, name of a sheet or file.

Methods represent the procedures that perform actions with the object, or to the
object. E.g. save or print a document.

Events can recognise and respond to an event. E.g. open a file, or before closing
a file.

Page 51
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Note this table and compare a car‟s objects, properties etc. to that in Excel or
Word.

Car Excel Word

Object The car itself Excel the program Word the program
A wheel A sheet A document
A door A chart A page
A tyre A cell A drawn object

Properties Colour of the car Name of a sheet Font of a word


Size of a wheel Font in a cell Size of a picture

Methods Open a door Save a workbook Close a document


Pressing the Print a worksheet Creating a new document
brake

Events Door open Sheet activate Document open


Key turn Selection change Document close

Collections Wheels Sheets Documents


Doors Charts Pictures

Topic B - Navigating the Object Hierarchy


The Object Model is the set of objects that an application exposes to the
development environment. Many objects are actually a collection of objects and
are very often a part of another object. The hierarchical relationship between the
objects of an application is very much the same as the relationship between the
folders and sub-folders on a computer – there is a parent-child relationship.

The . (full stop – referred to by developers as DOT) character is used to separate


the objects in a hierarchy as well as to separate the object from its built-in
properties and methods,
Application.ActiveWorksheet.Name = "Sales"
In the example above, Application is a parent object, ActiveWorksheet is a child
object, Name is a property and Sales is a text value to set the sheets name to.

Page 52
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Some of the objects that can be contained within a Worksheet object are shown
in the table below.

Object Content

Page Setup Controls how the document will be printed: header, footer, orientation,
Object zoom etc.

Chart object Containers for charts with this file allowing VBA to control all elements
within a chart.

PivotTable Allows VBA to manage a pivot table on the sheet.


object

Range object Controls how you can access a cell or manipulate a range of cells.

Cells object A collection of cells (in effect the entire sheet).

The Range object will refer to a cell or a group of cells, Range(“A1”),


Range(“A1:D2”) or Range(“A1”,”D2”).
Cells simply uses Row and Column numbers to refer to a cell for instance Cells(2,4)
or Cells(100,10).

Topic C - Understanding Collections


A collection is an object that contains a set of objects of the same type. An
individual object within the collection can change, therefore, the position of any
specific object in the collection can vary. Think of a sheet within the collection of
sheets and you are adding, removing or renaming just one sheet.

Many types of objects allow multiple occurrences – for example, Excel can
handle several open workbooks simultaneously – so it is useful to be able to refer
to the whole group of objects of the same type. The Collection provides this
facility, so that we can, for example, use the command Documents.Close to
affect all of the open Word files in one operation.

Naming of the collections is very straightforward – it is the plural of the elements


that it holds. E.g. WorkSheets is a collection that has every WorkSheet in an
open document.

Page 53
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Collection Properties and Methods


Collections have a set of special properties which differs from those of their
individual object. A useful property is the Count, with which you can always tell
how many members there are.
MsgBox Documents.Count & " documents are open"
All collections also have a special set of methods which includes Add, through
which a new member is created.
Sheets.Add or
WorkSheets.add ' create a new sheet
Collections may have methods specific to the elements that they hold.
Workbooks.Open "D:\DATA\TEST.XLS" ' open a workbook
Workbooks.Close SaveChanges:=True ' save and close all

Topic D - Accessing a Member of a Collection


Often you may need to single out an object within a collection – i.e. a sheet within
sheets. This is done by referring to its number in the collection, or to its name.

Names within a collection are not case-sensitive.

The full syntax is:


Collection.Item(Index) or
Collection.Item("Name")

It is permitted, and customary, to omit the .Item


Collection(Index) or
Collection("Name")

Page 54
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Understanding Collections

Scenario
This activity will take you through the process of understanding how a collection
of objects can use used within code.

Exercise
1. Before you begin, start a brand new file.
2. In the VB Editor, add a Module called modCollections.
3. Create the subroutine CollectionNumbers with no arguments.
4. Now Save the file as Module 3 Activities.xlsm.
5. Split the screen so you can see both Excel and VB Editor.
6. Enter the following code (run each line after you have typed it) to demonstrate
collections references numerically:
Sub CollectionNumbers()
Worksheets(3).Select
Columns(4).Select
Sheets(1).Select
End Sub
7. Check in Excel that the 4th column on the 3rd sheet is selected, now add the
following routine below CollectionNumbers.
Sub CollectionName()
Sheets("Sheet2").Select
Columns("B").Select
Rows("1:4").Select
End Sub

Page 55
QAVBA10INT v1.3 Introduction to VBA – Office 2010

8. Note the difference with the code, although the outcome appears similar,
finally add the following code.
9. This will show some of the methods for working with collections.

10. Split your screen to see both VB Editor and Excel, however in the VB Editor,
use the [F8] keyboard command to Step Through one line at a time.
Sub CollectionMethods()
Workbooks.Add
MsgBox Workbooks.Count
Workbooks(2).Close SaveChanges:=False

MsgBox Worksheets.Count
Sheets.Add
Sheets(Sheets.Count).Activate
End Sub

11. Note that Sheets/WorkSheets are similar, as are Select/Activate.


12. Save the file.
13. Leave the file open for the next activity.

Notes

www.qa.com

Page 56
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic E - Understanding Hierarchy


It is readily apparent that a hierarchy of objects exists, so that, for example, there
can be many sheets within a workbook. This leads to the principle of containment
of objects, and to a mechanism whereby an individual object can be
unambiguously accessed by specifying the hierarchy, using the dot notation.
Application.Workbooks("Test").Worksheets("Sales").Activate
You will notice that the notation takes us from the general to the specific – all
hierarchies originate at the Application object which owns the set of objects,
although it is usually possible to omit this from the line. If you know for certain
which object you have activated, you will usually shorten the reference.
Worksheets("Sales").Activate
Sometimes you will need to refer to the owner of a specific object; this reference
up the hierarchy is achieved by means of the Parent property. Thus the tree can
be navigated in either direction!
MsgBox ActiveSheet.Parent.Name ' display file name
It goes without saying that if you know the parent object name you can simply
use that in you code to produce similar results.
MsgBox Activeworkbook.Name ' display file name

Notes

www.qa.com

Page 57
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity - Understanding Hierarchy

Scenario
This activity will take you through the process of understanding objects and their
hierarchy a little better.

Exercise
1. Before we start, confirm that the Module 3 Activities.xlsm file is open.

2. In the VB Editor, within Module 4 Activities.xlsm, create a new module and


name it modParents.
3. Create the subroutine MyUnderstanding with no arguments.

4. Split the screen either vertically or horizontally so you can see both the Excel
and VBA Editor next to each other.
5. Type the following code inside your subroutine.
Application.Workbooks(1).Worksheets(2).Activate

6. Press [F5] from within the routine to run the code, note what happened in
Excel.
7. Type the following code inside your subroutine.
Worksheets(1).Activate

8. Run this and again note what Excel is doing, however the code is much
simpler.
9. Type the following code inside your subroutine.
MsgBox ActiveSheet.Parent.Name

10. Run this and read the message box.

Page 58
Introduction to VBA – Office 2010 QAVBA10INT v1.3

11. Finally type and run all the procedures the following code inside your
subroutine.
MsgBox Activeworkbook.Name

12. Save the file.


13. Leave the file open for the next activity.

Topic F - Using the Object Browser


When you are typing code and enter a dot the VB editor will usually give you a list
of the properties and methods of the relevant object from which to select.
However, in some cases it cannot tell what type of object you are dealing with,
and in that case it will not display a list.

In such cases the Object Browser gives a convenient means of checking the
available properties and methods. Think of the Object Browser as being a library
containing books relating to VBA. Within each book is an index of entries that
allow you to read help pages about the entry you wish to learn.

Figure 16 - Object Browser

Page 59
QAVBA10INT v1.3 Introduction to VBA – Office 2010

1. Start the Object Browser


 Select View, Object Browser from the menu, or

 Left-click the icon on the Standard toolbar , or


 Press [F2] key

2. From the Library drop-down you can select a particular library or leave a
default <All Libraries>.
 Select the object from the Classes list box
 Select the item from the Members list box (each type has a different icon)
You can see more details about the selected item in the bottom pane.

Icon Item

Method

Property

Constant

Event

Figure 17 - Icons within the Object Browser

A small cyan circle on the icon of a selected object indicates a default property. E.g.
the Value property of a TextBox object is a default property.
If you have the relevant object highlighted then use of the question mark symbol at
the top of the Object Browser will take you into Help for that Object/Property/Method

Page 60
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Using the Object Browser

Scenario
This activity will guide you through some questions that require the Object
Browser to find the answers to. Write answers on the _____ areas if you wish.

Exercise
Stay inside the VB Editor from the previous activity (Module 3 Activities.xlsm).
1. Press [F2] to access the Object Browser. How many libraries exist? ___

2. Right-click inside the Object Browser and select Group Members, and also
select Show Hidden Members.
3. From the Excel library, search for the word: Chart.

4. Scroll through the classes, turn off Show Hidden Members as there are too
many and are distracting.

5. Locate the word Trendline in the Classes List, in the Members select
DataLabel

6. Left-click on the Question Mark symbol alongside the libraries, read the help
for Trendline.DataLabel Property.
7. Can you set the Label or is it read only? __________
8. Left-click on the hyperlink that relates to the DisplayEquation property
9. Return to the Object Browser, and search for Border
10. How many properties (Members) does a border have? ___
11. Now search for MsgBox, what do you initially get?
12. Alter the Library to the VBA library, and search again.
13. Look for VBA, VbMsgBoxResult in the class with the top window

14. How many buttons (Constants - Members) can a Message box make potential
use of? _____

Page 61
QAVBA10INT v1.3 Introduction to VBA – Office 2010

15. Left-click, on a button in the bottom window e.g. vbYes, observe below there
is a numerical value for each button and then on the question mark for a
description of any of these.
16. Close Object Browser.
17. Leave the file open for the next activity.

Topic G - Using the With Statement


One useful statement for working with multiple properties/methods of an object is
the use of the With statement.

Syntax
With object
[Statements]
End With

This is particularly efficient when a series of operations are to be performed on


the same object, individual properties can then be accessed or methods applied
by just giving their name prefixed with a dot.
In the example below this shows a nested With statement. Within the Chart on a
sheet, the title, legend and axis title are set, also for just the chart title, the text,
and font settings are applied.

If nesting With statements, the use of indenting code will help you and others
understand how to read each nested block of code.
Example:
With ActiveSheet.ChartObjects("Sales").Chart
.HasTitle = True
With .ChartTitle
.Text = "This Months Sales"
.Font.Size = 14
.Font.Bold = True
End With

Page 62
Introduction to VBA – Office 2010 QAVBA10INT v1.3

.HasLegend = False
.AxisTitle.Text = "July Sales"
End With

Note the very concise programming style which this allows. With statements can
also be nested, i.e. one used inside another, as seen in the example above.

Remember to check each line within the With statement that the object which
you wish to manipulate is the one referenced in the With statement. If you want
to refer to a different object, just use normal hierarchy, without the dot at the
beginning.

Notes

www.qa.com

Page 63
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity - The With Statement

Scenario
This activity will demonstrate how a recorded macro will make efficient use of the
With Statement, which can then be edited by you. We will record a macro that will
set some Headers/Footers and then some borders in a file.

Exercise
Before we start, open and enable the Departmental Data.xlsm file.
Move the data sheet into the Module 3 Activities.xlsm file.
1. Record a macro called DemoWith.

2. From the Page Layout tab, access the Page Setup Dialog Box
(use the launcher in the lower right corner of the icon group).

3. Under the Header/Footer tab, left-click Custom Header add 'your company
name' in the Left section, and 'your name' in the right section.
4. In the Custom Footer add todays date in the right section.
5. Come out of Page Setup and select cells A1 to G1.

6. From the Home Tab, add an outside Thick Box Border around these cells,
then locate and left-click Merge & Center in the Alignment group of icons.
7. Stop recording, and Save the file.
8. We did 3 actions, how many lines of code do you predict were recorded?___
9. Edit the macro DemoWith.
10. Rename the Module to modWith if a new module was created by recording.
11. Note the overuse of With/End With.

Discuss which lines could be removed to make ease of managing easier within
the With ActiveSheet.PageSetup and also within the borders code.
12. Alter as required.
13. Save the file and leave the file open for the next exercise.

Page 64
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic H - Working with Properties


Objects do have a list of properties, although a list may contain only one element
– the property Name is common to all objects.

During the code execution you can read the property value, and very often also
change it too. Start with the name of the object and a dot, the properties will be
available to you (along with methods, see next section)

Syntax
Object.Property = Value

Where the value can be of different types:

Type Value

Number 23

Text “London”

Variable intPrice

Calculation intPrice*1.2

Function Format(intPrice, “0.00”)

Object.Property txtPrice.Value

To read a property value of an object, start with a method or a variable:


Example:
MsgBox ActiveSheet.Name
strName = ActiveSheet.Name

To change the property value of an object, finish with '= value':

Example:
ActiveSheet.Name = "My Test Sheet"

Page 65
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Boolean Properties
Consider the use of the standard Bold icon on the Ribbon in any application.
Click it once to set Bold = True. Click it again to change its property to be the
opposite i.e. False. The application changes the colour of the background of the
icon to identify whether it is True or False. This is known as a Boolean property.
The Visual Basic Editor displays True or False in the key colour Blue.

A very useful concept within macros is to toggle a Boolean property and therefore
both read and set the same property within a line of code. Consider you wish to
turn gridlines on/off in Excel.
ActiveWindow.DisplayGridlines = _
Not(ActiveWindow.DisplayGridlines)

In the above example, we make the DisplayGridlines property Not equal to its
current value, i.e. True become False or, False would become True.

To explicitly set the property regardless of its current state we could use the
following expression to turn off the gridlines.
ActiveWindow.DisplayGridlines = False

Notes

www.qa.com

Page 66
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Working with Properties

Scenario
This activity will confirm how properties can be read, set and also toggle if a
Boolean property is used.

Exercise
Work within the file Module 3 Activities.xlsm.
First, we look at reading properties
1. In the VB Editor, add a Module called modProperties
2. Create the subroutine ReadProperties with no arguments.
3. Type the following code:
MsgBox ActiveSheet.Name
MsgBox ActiveWorkbook.FullName

4. Run this code and note the message boxes,

5. Add some more property reading code within the same routine, comment
previous message boxes for ease of use
MsgBox ActiveCell.Address
MsgBox ActiveCell.Address(False, False)
6. Note the differences with the false arguments.
Now, we look at setting properties

7. Before we run this code split the screen so you can see the VB Editor and
Excel.
8. Select A1 in Excel on a blank sheet.
9. Enter the following code below the previous routine:

Page 67
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Sub SetProperties()
ActiveCell.ColumnWidth = 30
ActiveCell.Value = Now()
ActiveSheet.Name = "Training"
Sheets(2).Name = Application.UserName
End Sub

10. Run this code using [F8], and note all the changes, these show various ways
you can get properties updated.
Finally, we look at toggling a property
11. Type the following procedure below existing code.
Sub ToggleProperty()
ActiveWindow.DisplayGridlines = False
End Sub

12. Run the code and check the Gridlines are turned off
13. Now alter the code to read
ActiveWindow.DisplayGridlines = Not
(ActiveWindow.DisplayGridlines)

14. Run this code repeatedly and notice what is happening.


15. Save the file, leave open for the next activity.

Review Question: Name some other properties that are Boolean and therefore
can be toggled on and off?

Page 68
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic I - Working with Methods


Methods are the actions an object can perform. Most objects in VBA have
methods.

Syntax
Object.Method [arglist]
Start with the object name, follow by a dot operator, and then the method you
want to execute. This should be followed by the list of arguments separated by
commas.
Example:
ActiveWorkbook.PrintOut from:=1, to:=4, collate:=True

Named v Positioning Arguments


VBA requires the programmer to pass arguments in a certain order (by position),
some arguments could be omitted and defaults will be assumed, a comma has to
be included in the sequence of arguments to work as a separator.
The following example, demonstrates this approach:
Workbooks.Open "C:\temp\book1.xls", , True
VBA also has an alternative method of passing arguments by passing using the
named Argument as demonstrated below:
Workbooks.Open Filename:="C:\temp\book1.xls", ReadOnly:=True
This means that only the arguments which you wish to pass need to be supplied
(assuming that others are optional). The code is much more legible, and the
order of specifying arguments is not fixed.

It is vital to check that you name the arguments in the list to match Microsoft's
names in the QuickInfo. However, once you have written your own procedures, the
Intellisense system will pop up the names of their arguments and indicate any
optional ones, exactly as for the built-in procedures.

Page 69
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity - Understanding Methods

Scenario
This activity will confirm how methods can be set by using two different methods,
by position and by name.

Exercise
Stay in the file Module 3 Activities.xlsm.
First, we look at setting by position
1. In the VB Editor, add a Module called modMethods.
2. Create the subroutine MethodPosition with no arguments.

3. Write the code below, now as you write the MsgBox and PrintOut commands
looks at the QuickInfo. DO NOT RUN
Sub MethodPosition()
„ do not run
MsgBox "This is a Prompt", , "This is the Title"
ActiveWorkbook.PrintOut 1, 5, 3, , , , False
End Sub
Next, we look at setting by position
4. Now write the following code, and note the difference between these
statements. DO NOT RUN
Sub MethodNaming()
„ do not run
MsgBox prompt:="This is a Prompt", Title:="This is the
Title"
ActiveWorkbook.PrintOut copies:=3, collate:=False, _
from:=1, to:=5
End Sub

Page 70
Introduction to VBA – Office 2010 QAVBA10INT v1.3

5. Save the file, leave open for the next activity.

Topic J - Creating an Event Procedure


An event procedure is a subroutine that runs in response to an event. Users
trigger events all the time, and with effective use of VBA you a developer can
learn to „trap‟ these events and alter how they work.
To see the full list of available built-in events,
1. Access the VB Editor

2. From the Project Explorer, double-click on the Sheet you require, or the
option ThisWorkbook. If in Word, double-click on ThisDocument.
3. If code does not exist, select Worksheet or Workbook from the Object drop-
down list
4. Select the Event you wish to work in from the Procedure drop-down list.

Figure 18 - Workbook event procedure

5. In the example above, there are two workbook events being trapped, the
BeforePrint and the Workbook_Open events.

Their names are created automatically and consist of an object name, followed
by an underscore and the event. If required arguments may exist within the
brackets.

If an event has Cancel As Boolean in the brackets as an argument, you can write
Cancel = True in your code to actually cancel the event from happening.

Page 71
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic K - Reserved Macro Names


Some of you may remember AutoExec.Bat a Basic DOS file that if present would
run before Windows booted up. This was a reserved filename. VBA allows you to
create standard subroutines and make use of reserved names. If these
subroutines are present all code within will run automatically.

MS Office Reserved Macro Names


The following office applications have reserved macro names. When in Excel or
Word if you have both a reserved macro and an event, both sets of code will run.

Excel Word Access

Auto_Open AutoOpen AutoExec


Auto_Close AutoClose AutoKeys
AutoNew

With the exception of Access, reserved macro names are stored within standard
modules. These macro names are not case sensitive, but naming them as above,
helps with clarity.

Notes

www.qa.com

Page 72
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Events Handling

Scenario
This activity will show how private events can be set behind sheets/files and also
the use of reserved macro names that will run automatically.

Exercise
Stay in the file Module 3 Activities.xlsm.
1. In the VB Editor, add a Module called modAuto
2. Create the subroutine Auto_Open with no arguments.
3. Add a Message Box welcoming the user to the file.
4. Now add another subroutine called Auto_Close.
5. Add code to take you to Sheet 1, Cell A1
6. And a Message Box saying goodbye.
7. Save the file.
8. In Excel, Close and then Open the file.
9. Note the macros running automatically.
10. In the VB Editor, double-click on (Sheet2) within the Project Explorer window.
11. From the Object drop-down select WorkSheet.

12. You should be in the routine dedicated to SelectionChange, what do you think
this event traps?
13. Write the following code within the procedure:
MsgBox Target.Address
MsgBox Target.Value

14. These statements can trap what cell you have clicked into and observe its
value.
15. Alter the Procedure drop-down to Deactivate.

Page 73
QAVBA10INT v1.3 Introduction to VBA – Office 2010

16. Add a message box saying bye from the sheet


17. Note some of the other Procedures available
18. Now from Project Explorer, double-click on ThisWorkbook.
19. Select Workbook as the Object, note the procedure created.
20. Select BeforeClose procedure, and note the others starting with Before…
21. Also note how many more procedures there are available.
22. Select SheetActivate and then a simple message box.
MsgBox Sh.Name

23. In Excel switch between sheets, note the event is trapped.

24. If time permits, look at a blank Word document, and in the VB Editor observe
what procedures are available to ThisDocument.
25. Save and Close the file.

Notes

www.qa.com

Page 74
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Module 3: Review
This module was about:
 Understanding Objects Properties, Methods and Events
 Navigating the Object Hierarchy
 Understanding Collections
 Using the Object Browser
 Using the With Statement
 Working with Properties
 Working with Methods
 Creating an Event Procedure

Review Questions:
1. Name an Object within Excel we have not yet come across?
2. How is it easy to identify a collection?
3. What keyboard command opens the Object Browser?
4. What symbol throughout VBA dictates a Method and a Property?
5. If using a With statement what must be used to complete the syntax?

Notes

www.qa.com

Page 75
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Module 4 - Using Expressions, Variables and


Intrinsic Functions
This module will explain the needs and uses of variables within VBA. You will
also see functions that are within VBA to help you manipulate data. Using and
controlling message and input boxes are also covered.
By the end of this module you will have covered:
 Naming Rules
 Understanding Expressions and Statements
 Declaring Variables
 Understanding Data Types
 Determining the Value of Variables
 Using Built-in VBA Functions
 Understanding Constants
 Using Message Boxes
 Controlling the Answer to a Message Box
 Using Input Boxes
 Declaring and Using Object Variables

Topic A - Naming Rules


To be able to distinguish between different elements in VBA, all objects have one
property in common – their Name. The name of a user-defined object is
something that the programmer chooses, but there are well-defined rules which
you must follow when choosing a name. This applies to modules, subroutines,
functions, variables, forms, controls, etc.

Names can use any alphanumeric characters: letters between A and Z inclusive.
You can also use the digits 0-9 and the underscore character, but the latter two
are not allowed as the first character of a name. The first character of the name
must be a letter. You cannot use a space, full stop [.], exclamation mark [!], or the

Page 76
Introduction to VBA – Office 2010 QAVBA10INT v1.3

characters [@], [&], [$], [#] in a name. The best option is to stick to letters and
numbers.

There are some keywords (VBA reserved words) which may not be used as names,
like If or New. Although some can be used, it is best to avoid any keywords.

VBA does not make any distinction between upper and lower case, so you can
capitalise the name in any way you choose, but again it would be better to stick to
a consistent rule so that the code is much easier to read. A recommended logic is
to use „CamelCase‟ where the first letters of words that are used in a name are in
upper case while all the other characters are in lower case.
When naming some items, like variables and controls, it is a good policy to
precede a name with a 3 letter prefix that indicates the type of the object.

Any chosen name should also be descriptive. A descriptive name will help you
(and others) read and understand the program later.

A name cannot exceed 255 characters in length, but there should never be a
need to have names of that length!

Valid names Invalid names


XYZ HowTo$u¢¢eed
NumberOfCDs @Count of CDs
Chlor_Conc Chlorophyll Concentration
FirstQtr 1stQuarter
Qtr1Report _initialise

A descriptive name will help you (and others) read and understand the program
later. If it‟s a procedure or function use a verb in the name.
As a rule of thumb, try to avoid names which are very short or very long.

Within a project you can have repeated names of existing macro procedures in
other modules. VBA can distinguish them within each module. However this is
not best practice, and worth avoiding.

Page 77
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic B - Understanding Expressions and Statements


An expression is a combination of keywords, operators, variables, and constants
that returns a string, a number, or an object. An expression can be used to
perform a calculation, manipulate characters, or test data.

Numeric Expressions – Calculations


Numeric expressions can be made from any combination of variables, constants,
operators and built-in functions.

Symbol Mathematical Operators

+ Addition

- Subtraction

* Multiplication

/ Division

\ Integer division

MOD Remainder after division

^ Raise number to the power of

As with algebra, multiplication and division have a higher precedence than those
of addition and subtraction. This precedence can be overridden using brackets
e.g.
p=2+x*5 or p = (2 + x) * 5

String Expressions
A string expression is any expression that evaluates to a sequence of contiguous
characters. Elements of a string expression can include a function that returns a
string, a string literal, a string constant, a string variable, a string variant, or a
function that returns a string variant.
strUserName = strFirstName & " " & UCase(strSurname)
strUserName = LCase(Left(strFirstName,1) & strLastName)

Page 78
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Statements
A statement is a syntactically complete unit that expresses one kind of action,
declaration, or definition. In simple terms it is another word for a line of code, or a
single procedure.

A statement generally occupies a single line, although you can use a colon [:] to
include more than one statement on a line.

Code does not 'wrap' like a word document with paragraphs, so to assist
developers with wrapping code making it easier to read, VBA makes use of an
underscore (_) character. The underscore will allow as many lines as you like to
wrap together. There are some rules that must be adhered to.
 You must have a space before the underscore character

 You cannot have and underscore between a pair of quotation marks e.g.
"Text _
 You must close quotes, add a space, then the underscore, e.g. "Text " _
On the following line use an ampersand & to join text back together similar to
below
Dim intAge As Integer
intAge = 24
strName = UCase(Left(strName),1) & LCase(Mid(strName,2)) & _
" is " & intAge & " years old"

The macro recorder often makes use of an underscore to „word wrap‟ lines of code.

Page 79
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Numeric Expressions (Calculations)

Scenario
This activity will demonstrate why calculating in VBA with numbers is important,
especially if you are doing complex formulas, and, like Excel, the use of brackets
dictate the answer.

Exercise
Before you start, close any open files in Excel, start a new blank file.
1. In the VB Editor, add a Module called modMaths.
2. Insert a Procedure called subMaths.
3. Save the file as Module 4 Activities.xlsm.

4. You do not need to enter all the comments they are here for reference
purpose.
5. Enter the following code:
Sub subMaths()
' My total is 1000, less a 100 discount and add VAT at 20%
' What is the amount of VAT to be calculated

' Simple VAT calculation, an amount, less discount, VAT


added
ActiveCell.Value = 1000 - 100 * 0.2

' Similar calculation to get result, note difference


ActiveCell.Offset(1).Value = (1000 - 100) * 0.2
End Sub
6. Run this code and note the values Excel shows, clear the values off the Excel
sheet.
7. Save this file for later use.

Page 80
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic C - Declaring Variables

Understanding Variables
Most programming languages provide the concept of variables. Think of a
variable as a portion of the computer's memory, which can hold a piece of
information.

Syntax
Dim varname [As Type]
Each variable has:
1. Name (varname)

The name is required so that VBA can access the variable after it has been
created. Variable names must be unique within a given section of program code
to avoid ambiguity.

When naming variables, use similar logic to that of naming conventions for
macros and modules.
2. Type

The type is optional, although recommended, so that VBA knows the kind of data
to be stored in the variable. With this information, VBA can set aside the correct
amount of memory for the variable and check that the program is performing valid
actions on the data in that variable.
3. Value

The value is set later in code. As the code runs, the variable may have different
values stored in it. Hence the value may vary.

If Require Variable Declaration is checked on within the VB Editor Options, then


Option Explicit appears at the top of each module. This forces a developer to use the
Type setting of all variables

Page 81
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Declaring a Variable
Variables should be created before they are used within a program. This process
is known as Declaring the variable. When declaring a variable, the programmer
states the name of the variable and, optionally, the type of information it can hold.

The programmer can declare many variables and each one will have its own
name and type. Variable declaration is either performed in the General
Declarations area, or logically at the top of procedures.

The most common VBA statement that declares a variables is the Dim
statement. The keyword Dim (short for Dimension). This tells VBA to set aside a
portion of memory for your variable. All the developer needs to specify is the
variables name and type, and VBA does the rest for you.

The Dim keyword is followed by the name of the variable. The keyword As
separates the name of the variable from the type clause which completes the
statement. For example:
Dim intNoOfCDs As Integer
Dim strUserName As String
Rather than write multiple Dim statements, VBA allows you to merge multiple
variable Dim statements separating each with a comma. So the lines above could
also be written as:-

Dim intNoOfCDs As Integer, strUserName As String

All variables are given an initial value when they are created. Numeric variables
are initialised to zero and String variables are initialised to an empty string. As
execution of program code continues, the program can read from and write data
to the variable.

If you omit the type of the variable when declaring it, it would be given a generic type
called a Variant and it would not be given an initial value so it would return an
Empty value.

Assigning a Value to a Variable


Variables are of no use unless we can read and write their contents. In order to
write a value to a variable, VBA formally uses the optional Let keyword and the
equals sign [=]. When VBA encounters this statement, it calculates the value on

Page 82
Introduction to VBA – Office 2010 QAVBA10INT v1.3

the right side of the = and stores the result to the variable whose name appears
on the left side of the = sign (so the equals sign is best read as 'becomes').
Example:
Dim intNoOfCDs As Integer
Let intNoOfCDs = 34

When the statements in the example above are executed, the old value of the
variable intNoOfCDs (whatever that might be) is overwritten with the new value
(34). The old value held in variable intNoOfCDs is lost.

The technical term is for this operation is Assignment. It is said that the value 34
is assigned to the variable intNoOfCDs. For this reason, the equals sign (as
used here) is sometimes called the assignment operator.
intNumberOfCDs = intNumberofCDs + 100 ' Let is optional

When the statement in the example above is executed, the old value of the
variable is overwritten with the new value. Therefore 100 is added to the current
value. The old value held in variable intNoOfCDs is lost.
The use of the Let statement is optional and normally disregarded.

Notes

www.qa.com

Page 83
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Declaring and Using Variables

Scenario
From the previous activity, we will convert the code to now make use of
Variables.

Exercise
Before we start, confirm you have Module 4 Activities.xlsm open.

1. In the VB Editor, Copy and Paste the entire subMaths routine, and rename
the new one to subVariables.
2. Remove any comments and just keep the two lines of code.
3. Alter the code as follows:-
Sub subVariables()
Dim bytDiscount As Byte
Dim sngVAT As Single
Dim sngVATAmount As Single
bytDiscount = 100
sngVAT = 0.2

ActiveCell.Value = 1000 - bytDiscount * sngVAT


sngVATAmount = 1000 - bytDiscount * sngVAT

ActiveCell.Offset(1).Value = (1000 - bytDiscount) *


sngVAT
sngVATAmount = (1000 - bytDiscount) * sngVAT

MsgBox sngVATAmount
End Sub

Page 84
Introduction to VBA – Office 2010 QAVBA10INT v1.3

4. Run this code and note the values Excel shows, clear the values off the Excel
sheet.

5. Inside this procedure, use [F8] and step through this procedure, with your
mouse place it over the sngVATAmount variable as you run through each line
of code.
6. Save this file for later use.

Topic D - Understanding Data Types


With the correct type set, VBA can set aside the correct amount of memory for
the variable and check that the program is performing valid actions on the data in
that variable.

The type is required so that VBA knows the kind of data which is to be stored in
the variable.

Supported Data Types

Type Memory Size Decimals Value Range Prefix

Boolean 2 bytes True/False bln

Byte 1 byte 0 0 to 255 byt

Integer 2 bytes 0 -32,768 to 32,767 int

Long 4 bytes 0 -2.1*109 to 2.1*109 lng

Single 4 bytes 7 -3.4*1038 to 3.4*1038 sng

Double 8 bytes 15 -1.8*10308 to 1.8*10308 dbl

Currency 8 bytes 22 -9*1014 to 9*1014 cur

Date 8 bytes 1/1/100 to 31/12/9999 dat

String 1 byte/char 0 to ~63,000 str

16 bytes or 22 bytes+1
Variant var
byte/char

Page 85
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Users of Microsoft Access will recognise some of these data types and their value
ranges as they are similar to the Size property of fields within a table.

Use the prefix when naming variables so that you (and the others) will know what
kind of data is stored.

Type Mismatch Error


If, when the program is running, a string value is assigned to a numeric value,
VBA will try to convert the value to the correct type. This cannot always be done
– for example if a numerical value contains characters other than figures 0 to 9.
Dim bytNoOfCDs As Byte
bytNoOfCDs = "More than 50"

Technically there is nothing wrong with the syntax of the statements, until the
computer tries to execute the code. In the above case, you will see an error
appear at run-time (that is, when the program is running rather than when the
program is being written by the programmer). This error message is „Type
mismatch‟.

Overflow Error
This error type usually arises through the programmer choosing assigning a
value to a variable outside the value range specific for that data type (see the
table above).
Dim bytNumberOfCDs As Byte
bytNumberOfCDs = 200 + 250 ' two values added
together
The above case will trigger an „Overflow‟ runtime error since you can only store
whole numbers from 0 to 255 in a Byte type variable.
Technically again, there is nothing wrong with the syntax of the statements, until
the computer tries to execute the code. This reflects the fact that it is an
„interpreted language‟ – meaning that it never reads ahead to see what might
happen next.

Page 86
Introduction to VBA – Office 2010 QAVBA10INT v1.3

On the other hand, the editor DOES pick up incomplete statements or


punctuation errors as you try to move the cursor off the current line of code.

Excessive use of Variant data type will make an application slow because Variant
type consumes a lot of memory and VBA needs to check the value and the type.

Compile Error
Whilst typing in the VB Editor, VBA will constantly check the code being written
for errors. The most common typing errors may result in a 'compile error', this
error must be resolved before any code can be run. With variables this can be
mistyping the name of a variable thought a procedure, or mistyping the type of
variable being used.
If the name of the type is spelled incorrectly, it will not be recognised, and VBA
will give the compile error message „User-defined type not defined „. This
message is not very helpful; it arises because VBA assumed that the incorrectly-
spelled type name is meant to be a special type of variable declared somewhere
else by you.
Dim bytNoOfCDs As Intiger
The above case will trigger a „Compile „ runtime error since the VBA is not able
to find the Integer type of variable. The fact you have used int as a prefix to the
name of the variable does not affect anything. A variable could be called
bytElephants, but the type dictates what it is holding.

To check for such errors within the VBA Editor select the Debug menu and select
Compile Project. If VBA can identify errors, then you will see them. If Compile is
greyed out and unavailable, then there are no issues detected with your code.

The use of Debug, Compile is exceptionally useful when identifying an error not
easily spotted. For instance you may have a long With statement and missed the
End With statement. For variables it is easy to mistype them, they must be the same
as the Dim statement.

Page 87
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Managing Variables and Basic Error Management

Scenario
From the previous activity, we will alter some values and note the errors that
happening, we will touch upon an error handling routine that notices errors in our
handling of variables.

Exercise
Before we start, confirm you have Module 4 Activities.xlsm open.
1. In the VB Editor, alter the bytDiscount variable to be 300.
2. Run the Code, and note the error, select End within the error box.
3. Use either Undo or manually edit the line back to 100.
4. Alter the code to the word Singel (misspelt) for either of the Dim statements.
5. Run the code, note you get a compile error.
6. Reset back to Single.
7. Comment out any of the Dim lines, (imitates not running by turning into
comments).
8. Use the Debug menu and select Compile.

9. Note it traps an error, however now comment the Option Explicit from the
General Declarations.
10. Use the Debug menu and select Compile, do you get an error this time?
11. Display the Immediate Window and add the following code below the MsgBox:
Debug.Print sngVATAmount
12. Run the routine again, note what is displayed in the Immediate Window.
13. Close the Immediate Window.
14. Save the file. Leave the file open for the next activity.

Page 88
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic E - Determining the Value of Variables


As part of debugging it is sometimes useful to display the values of variables and
expressions while the code is executing.
This can be achieved by using the following VBA tools:

1. Locals Window

Displays the value of variables and properties.

2. Immediate Window – {CTRL} + [G]

Executes code one statement at a time.

3. Watch Window

Displays the value of each expression added to the window.

4. Quick Watch –{SHIFT} + [F9]

Displays the value of a selected expression or variable when it cannot be


evaluated automatically (by placing the mouse cursor over the statement).

More about Locals, Immediate and Watch Windows, see notes on the Debugging
and Error handling module.

Working with Variable Scope


When you create a variable with the Dim statement, the variable is available in
the environment where that statement is. E.g. a variable created in a procedure is
available to that procedure only, and a variable created at the top of the module
(General Declarations) is available to all the procedures in that module only.

Shared Variables
Variables declared in the General Declarations area are often referred to as
Shared Variables, hence multiple procedures can share the value of the variable.

Page 89
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Option Explicit
Dim bytDecimals As Byte

Sub optTwo_Click()
bytDecimals = 2
Call CmToIn(bytDecimals)
End Sub

Sub CmToIn(sngCm As Single) As Single


CmToIn = sngCm / 2.54
MsgBox "Converted to " & CmToIn
End Sub

You can increase the scope of a module-level variable by declaring it with the
Public keyword, instead of Dim. This variable will then be available to all
procedures in all modules.
Module 1 Module 2

Option Explicit Option Explicit


Dim strUser As String -------------------------------
Public tmLogIn As Date
------------------------------- Sub UsingMacro()
‘ I will only see tmLogin variable
Sub TestMacro() End Sub
Dim strCompany As String
‘ I will see all three variables
End Sub

Figure 19 - Variable scope

Page 90
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Altering Variable Scope

Scenario
The Dim statements are only working at the Procedure level, we will in this
activity place them in the General Declarations area to make them work across
the entire Module.

Exercise
Before we start, confirm you have Module 4 activities.xlsm open.

1. In the VB Editor, Cut the 3 Dim statements and paste them into the General
Declarations area, below Option Explicit.

2. Alter end of the subVariables procedure to call another procedure and reuse
variables that have already been set. Write the following code, from the
bottom of SubVariables, only add the Call line.
Debug.Print sngVATAmount
Call subNextCode
End Sub
____________________________________________________________
Sub subNextCode()
MsgBox "The VAT Amount is " & sngVATAmount
End Sub
3. Run the subVariables Procedure, and the variable being set in one procedure
should now appear in a message box in another.
4. Close the Immediate Window.
5. Move the Dim statements back within the SubVariables procedure.
6. Right-click on each variable name and select Add Watch, OK.
7. Step through the code for SubVariables, observing the Watch Window.
8. Move the Dims back to the top of the Module.

Page 91
QAVBA10INT v1.3 Introduction to VBA – Office 2010

9. Repeat the adding to Watch Window and also the stepping through
SubVariables
10. Save the file.
11. Leave the file open for the next activity.

Topic F - Using Built-in VBA Functions


Like Excel and Access, VBA contains many built in functions (often referred to as
intrinsic functions). Some names are the same as Excel/Access, however others
although they work the same way are named slightly different.

Here is a categorised list of some of the more common VBA Functions, their
syntax and a brief description:-

Maths Functions
Round (number [,numdecimals])
Returns a number rounded to a specified number of decimal places.
number Number or a numeric expression being rounded.

Numdecimals Optional. A number indicating how many places to the right


of the decimal are included in the rounding, If omitted, 0 is used as default.
Int(number)
Rounds a number down to an integer.
number Number or a numeric expression.

Int is often thought to only show the integer part of a number i.e. 5.9, 5.5 or 5.1 all
become 5. However -5.1, -5.5 and -5.9 would all become -6. Confirming that Int
rounds down.

String Functions
Len(string)
Returns the number of characters in a string.
string Text from which the number of characters is returned.
Left(string [,length]) or Right(string [,length])

Page 92
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Returns the text based on the specified number of characters from the left or the
right side of a string.
string Text from which the leftmost or rightmost characters are returned.
length Number indicating how many characters to return.
Mid(string, start [, length])
Returns text from the middle of text, based on a specified number of characters
and its starting location
string Text from which the specific characters are returned.
start Character position in string at which the part to be taken begins.
length Number indicating how many characters to return.

If you omit the second argument (Length) from Left or Right then the function will
only return 1 character. The leftmost or rightmost letter.
If you omit the third argument (Length) from Mid function, all characters from the
start position to the end of the string are returned (similar to the Right function).
Mid("impress",3) will return press

LCase(string) or UCase(string)
Converts a string to lowercase or uppercase
InStr([start, ]string1, string2[, compare])
Returns the position of the first occurrence of one string within another.
start Optional. Sets the starting position for the search. Instr will start with the
first character in the string if omitted.
string1 The text being searched.
string2 The text being sought.
compare. Optional. Beyond the scope of this course

Date Functions
Date()
Returns the current system date.

Page 93
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Now()
Returns the current system date and time.

For both the Date and Now functions, VBA may omit the empty brackets.

Weekday(date [, firstdayofweek])
Returns a whole number representing the day of the week between 1 and 7. By
default Sunday is 1.
date The date being analysed
firstdayofweek Optional. This allows you to change what day 1 is.
Day(date)
Returns a whole number representing the day 1-31 of the given date.
Month(date)
Returns a whole number representing the month 1-12 of the given date.
Year(date)
Returns a whole number representing the year.
date Date from which the number representing year is returned.
DateSerial(Year, Month, Day)
Returns a Date for a specified year, month, and day. Year, month and day are all
numerical values.

It is worth using VBA help to explore other date functions, such as DatePart,
DateAdd and DateDiff.

Conversion Functions
When assigning the value of an expression to a variable the expression may be
of a different type from the variable. VBA will perform this type conversion
invisibly – you can, for example, assign the value from a double to a currency
variable. Similarly you can assign a numeric value to a string variable, and it will
be converted using default formatting.

Page 94
Introduction to VBA – Office 2010 QAVBA10INT v1.3

You may need to convert from one type to another explicitly if the required
conversion is not clear to VBA from the context.

The conversion functions have names which start with 'C' and (usually) three
characters indicating which conversion is intended (the 3 characters we use as
prefix when naming variables). Thus CInt(exp) converts to an integer; CDbl(exp)
converts to a double, CStr(exp) converts to string, etc.

VBA also retains its original Val(exp) function, which converts text to numbers
(and will, for example, handle the extraction of 123 from 123abc, where CInt(exp)
would not). There is also Str(exp), which converts anything numeric to text.
This is a complete list of the Type Conversion Functions from VB Help.

Syntax
CBool(expression)
CByte(expression)
CCur(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CSng(expression)
CStr(expression)
CVar(expression)
The required expression argument is any string or numeric expression.

One other useful function is Format. The Format function will allow you to
display a value in the specified format.
Format(expression [, format])
expression Any valid expression.
format Optional. A valid named or user-defined format expression.

Page 95
QAVBA10INT v1.3 Introduction to VBA – Office 2010

If you are familiar with custom number formatting in Excel you can use the same
codes as the second argument within Format function.
Format(87654.321, "£#,##0.00"
will return £87,654.32

Notes

www.qa.com

Page 96
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Using VBA Functions

Scenario
This activity will introduce you to some of the functions built into VBA.

Exercise
Before you start, move onto Sheet2 in Module 4 activities.xlsm and in A1 enter
your Name, in A2 enter your Date Of Birth.
1. In the VB Editor, insert a new Module, called modFunctions.
2. Create a procedure called subFunctions.
3. Enter the following code:
Sub subFunctions()
Dim strName As String, datDOB As String

strName = Range("A1").Value
datDOB = Range("A2").Value

Range("B1") = Left(strName, InStr(1, strName, " ") - 1)


Range("C1") = Right(strName, Len(strName) - InStr(1,
strName, " "))

Range("B2") = Day(datDOB)
Range("C2") = Month(datDOB)
Range("D2") = Year(datDOB)

End Sub
4. Debug and Compile the code and check for errors.
5. Run the code and note Sheet2.
6. Save the file.

Page 97
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic G - Understanding Constants


A constant is a named item (similar to a variable) that retains a constant value
throughout the execution of a program. Unlike a variable, a constant does not
and cannot change its value, hence it is constant.

Syntax
[Public] Const constname [As Type] = expression
When declaring a constant, unlike a variable, you set the value of the constant on
the same line as you define the constant and the data type for it.
Example:
Const VAT As Single = 0.2
Const PI As Single = 22/7
If you know you are going to make use of constants throughout code, then in a
separate moduledeclare them as Public constants.

Creating a Constant
Constants can be defined by the developer using the Const statement. You can
use constants anywhere in your code in place of actual values. Const statements
are often declared like variables within the General Declarations area of a module
making them available to all procedures within the module.

Using Built-in VBA Constants


An intrinsic constant is a constant provided by an application. Visual Basic
constants are listed in the object library and can be viewed with the Object
Browser.
Each host application has its own set of built-in constants, these all begin with a
two letter code such as vb, xl, wd or ac thus helping you to identify which
applications constant it is.

Page 98
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Some examples of constants throughout MS Office are:

VBA Excel Word Access

vbNewLine xlPaperSize wdBreakType acFindMatch


vbRed xlChartType wdFieldShading acPrintRange
vbYesNo xlTrendlineType wdReplace acView

There are hundreds (if not thousands) of built in constants, in essence they are
nothing more than a numerical value, however, the words are more meaningful
than a number helping developers understand code better. E.g. vbYes has the
value of 6.

Because you cannot disable intrinsic constants, their names are like keywords and
consequently you cannot create a user-defined constant (or any other element) with
the same name.

Notes

www.qa.com

Page 99
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Using Constants

Scenario
As VAT is set at 20% we will change the Dim statement to a const and write the
correct syntax for this.

Exercise
Before we start, confirm you have Module 4 Activities.xlsm open.
1. In the VB Editor, display the procedures in modMaths.
2. Within General Declarations alter the Dim statement for sngVAT to
Const sngVAT As Single
3. Now remove the line of code within subVariables which states sngVAT = 0.2.
4. Note the const line is in Red – signifying an error, why?
5. Add = 0.2 to the end of the const line.
6. Debug and Compile the code and check for errors.
7. Save the file.

Topic H - Using Message Boxes

Communicating with the End-User


One of the most commonly-used VBA commands is MsgBox, which displays a
simple dialog. By its nature, any dialog displayed in Excel stops the execution of
the underlying macro until the end-user dismisses it from the screen.

Syntax
As a function:
MsgBox(prompt[, buttons] [, title] [, helpfile, context])

Page 100
Introduction to VBA – Office 2010 QAVBA10INT v1.3

This may appear confusing as it suggests that MsgBox should be followed by a


bracket. That is true when MsgBox is used as a function for decision making, but
not when it is used to output a message (a method).

Argument Definition

prompt The message being displayed

buttons Optional. Choice of button to the user, default is


only OK.

title Optional. The heading over the top of the message.


If blank the Microsoft application title is used.

helpfile Optional. A compiled help file, file developed for


using if a user required detailed help

context Optional. If a help file is used the link to the specific


help to show a user.

Both helpfile and context are beyond the scope of this course.
Syntax
As a method:
MsgBox prompt, [, title] [, helpfile, context]
The simplest form of the command is MsgBox “Message” which causes the box
to be presented with just the specified message, an OK button and the relevant
Microsoft application title.
Example:
MsgBox “Hello World!”

Figure 20 - Sample message box

Page 101
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Message Box Options


The arguments of the MsgBox function allows the developer to specify not only
which buttons should be displayed, but also any warning icon and also the
highlighting of one button to set as a default (i.e. the one which is triggered if the
user presses [Enter]).

The Prompt argument of a MsgBox can be built up to more complex statements.


This is done by concatenating the text strings together by using the [&] operator.

You can also display the prompt text within the MsgBox on several lines by
including the vbNewLine constant in the string:
MsgBox "Balance is:" & vbNewLine & intBalance

Some developers will use alternatives to the vbNewLine constant, vbCr, vbLF or
vbCrLf are other constants that could be used. Another function the works similar is
the use of Chr(10) and Chr(13). In essence all these alternatives do the same as
vbNewLine.

The Buttons argument is a number, but for clarity the use of VBA constants with
sensible names will make a message box easier to interpret by developers. They
are organised so that you can add together all the required options (i.e. part
specifying the buttons, the part specifying the icon and the part indicating the
default button, in any reasonable combination).

Value Contant Displays

0 vbOKOnly
1 vbOKCancel
2 vbAbortRetryIgnore
3 vbYesNoCancel
4 vbYesNo
5 vbRetryCancel
16384 vbMsgBoxHelpButton

Table 1 - Options for buttons display

Page 102
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Value Constant Displays

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

Table 2 - Options for icon display

Value Constant Default Button

0 vbDefaultButton1 First button set as default

256 vbDefaultButton2 Second button set as default

512 vbDefaultButton3 Third button set as default

768 vbDefaultButton4 Fourth button set as default

Table 3 - Options for default button

Examples:
MsgBox (“Ok to carry on”, vbYesNo + vbCritical + _
VBDefaultButton2)
Or exactly the same:-
MsgBox (“Ok to carry on”, 276)
Both of the examples above if typed in Word will produce the following MsgBox.

Figure 21 - Sample MsgBox arguments

Page 103
QAVBA10INT v1.3 Introduction to VBA – Office 2010

The Title argument is a string that can replace the name of the application over
the top of the MsgBox when displayed.
Example:
MsgBox "Today is Friday", , "What day is it?"

The Title argument cannot have multiple lines of text unlike the Prompt argument
which can.

Topic I - Controlling the Answer to a Message Box

Returned Values
When the MsgBox is used as a function, it returns the value of the button that is
clicked. You can reference this value by number or by its corresponding constant
(see Table 4).

Button Selected Constant Returned Value

vbOK 1

vbCancel 2

vbAbort 3

vbRetry 4

vbIgnore 5

vbYes 6

vbNo 7

Table 4 - Returned values

Page 104
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Consider storing the result of a message box inside a variable then the variable
could be used throughout your procedures. For instance:-
Sub LongMacro()
Dim bytAnswer As Byte
bytAnswer = MsgBox(“Continue with Process”,vbYesNo)
[Statements]
If bytAnswer = vbNo Then Exit sub
[Statements]
End Sub

Notes

www.qa.com

Page 105
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Understanding Message Boxes

Scenario
We have been using message boxes throughout code, now is time to delve into
more details. This activity will explore more advanced things a message box can
do. We will also use message box as a function.

Exercise
Before we start, confirm you have Module 4 Activites.xlsm open.
1. In the VB Editor, create a new module and name it modMessages.
2. Create a Procedure called subMessages.

3. Enter the following message box testing out the possibilities within the
arguments:
Msgbox “Are you sure”, vbYesNo + vbCritical +
vbDefaultButton2

4. This message box now has an image, and a second default button of No.
5. Add a simple message box underneath.
Msgbox “This represents” & vbNewLine & “Any code…”
6. Alter the procedure to read:
Sub subMessages()
Dim bytResponse As Byte

bytResponse = MsgBox("Are you sure", ……………


vbDefaultButton2)
If bytResponse = vbNo Then Exit Sub
MsgBox "This Represents....”

End Sub
7. Save and Run the code.

Page 106
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Dependant on you clicking on either Yes or No will dictate if the code gets to the
second message box.

Review Question: What does the value 273 equate to in a message box
(use the table in the manual)?

Topic J - Using Input Boxes


InputBox is a built-in VBA and Excel function that prompts the user to enter a
value inside a dialog box that appears with a prompt and OK and Cancel buttons
(unlike MsgBox function, you have no control over the buttons displayed).

InputBox as a stand-alone function is used only in simple cases, because it is not


practical to ask the end-user lots of separate questions. More sophisticated
programs usually create their own forms.

Syntax
InputBox(prompt[, title] [, default] [, xpos] [, ypos] [,
helpfile, context])

Notes

www.qa.com

Page 107
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Argument Definition

prompt The message being displayed. This setting is the same as a Message
box.

title Optional. The heading over the top of the message. If blank the Microsoft
application title is used. This setting is the same as a Message box.

default Optional. String expression displayed in the text box as the default
response if no other input is provided. If you omitted, the text box is
displayed empty.

xpos Optional. A value measured in twips (a unit of screen measurement equal


to 1/20 point). It represents the horizontal distance the left edge of the
screen. If omitted then the box is centred horizontally.

ypos Optional. A value measured in twips. It represents the vertical distance of


the top of the screen. If omitted then the box is positioned approx. 1/3rd
down the screen.

helpfile Optional. A compiled help file, a file developed for using if a user
required detailed help. This setting is the same as a Message box.

context Optional. If a help file is used the link to the specific help to show a user.
This setting is the same as a Message box.

Both helpfile and context are beyond the scope of this course.

Example:
Dim intAge As Integer
intAge = InputBox("How old are you?")
MsgBox "Next birthday you will be " & intAge + 1

Figure 22 - Sample input box

Page 108
Introduction to VBA – Office 2010 QAVBA10INT v1.3

If you use VBA Help you may find Application.InputBox, within Excel, VBA allows
another choice of InputBox.
It displays slightly different, however a user can actually click on a cell to select the
value of the InputBox. Additionally there is another optional argument that dictates
what data type the value must be.

Checking End-User Input – Was Anything Typed?


Good practice is to check that the results of an InputBox are valid before
executing further code. VBA can make use of error handling the users response,
the first thing that should always be checked is to see whether or not anything
was entered in the first place.

VBA will record an 'empty string' if the Cancel button is used or the box is left
empty an OK button is used. The following example shows a test for the empty
string and uses Exit Sub to avoid any further statements, and if NOT empty then
the response will be converted into an Integer:
Dim strResponse As String, intAge As Integer
strResponse = InputBox("How old are you?")
If strResponse = "" Then Exit Sub
IntAge = CInt(strReposonse)

You can record InputBox results into other variable data types, but the use of String
will help to trap Cancel or nothing being entered easier.

Page 109
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Using Input Boxes

Scenario
We have been using message boxes throughout code, now is time to delve into
input boxes and their interaction with the users.

Exercise
Before we start, confirm you have Module 4 Activities.xlsm open.
1. Create a Procedure called subInputs.
2. Write the following code:-
Sub subInputs()
Dim intAge As Integer
intAge = InputBox("How old are you?")
MsgBox "Years to retire: " & 60 - intAge
End Sub
3. Save the file.
4. Run the code, enter your age into the input box.
5. Alter the Title argument to 'Retirement Calculator'
6. Save the file.

Page 110
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic K - Declaring and Using Object Variables


As so much of the code that we write in VBA manipulates the objects of the host
application, it is useful to be able to point to individual objects. For this purpose,
the object variable is provided so developers can store entire objects within
procedures in a similar way to variable store values.

Object variables are declared in exactly the same way as other variables (either
within a procedure or in the global declarations within a module), you specify the
most appropriate type of object that you want to use with an appropriate name.

Syntax
Dim objname [As ObjectType]

If you know that an object has a specific type (such as a Range, a Control or a
WorkSheet), the compiler will handle the variable most efficiently if you specify
this in the declaration, and you will also benefit from the closer type-checking and
better help from the editor. But if you are not sure of the type then As Object
should be specified.
Example:
Dim conButton As Control
Dim ws As WorkSheet
Dim objXYZ As Object

Object type can include the library name to avoid ambiguity.


Dim appExcel As Excel.Application

Assigning Value to an Object Variable


To assign the value to an Object Variable you must use the Set keyword and
provide a description of the object. Unlike Let being optional for variable
declaration, Set is mandatory for assigning objects.
Example:
Set appExcel = CreateObject("Excel.Application")
For efficiency, you need to point as far down the hierarchy as possible. Thus, it is
better to set up the object variable to point to a range whose properties are to be

Page 111
QAVBA10INT v1.3 Introduction to VBA – Office 2010

altered than to point to the worksheet and then have to evaluate the range
several times.

Dim R As Range
Set R = Workbooks("Demo").Worksheets("Data").Range("A5")
R.Value = 100
Best practice dictates object variables are set to Nothing when their use is
complete. There is a possibility of VBA keeping in memory an invisible copy of an
object variable, this could lead to damaging the object and to reduced
performance.

So within your closing statements a command such as the one below should be
used.
Set appExcel = Nothing

Module 4: Review
This module was about:
 Naming Rules
 Understanding Expressions and Statements
 Declaring Variables
 Understanding Data Types
 Determining the Value of Variables
 Using Built-in VBA Functions
 Understanding Constants
 Using Message Boxes
 Controlling the Answer to a Message Box
 Using Input Boxes
 Declaring and Using Object Variables

Page 112
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Review Questions:
1. Of these variable names which would be valid? 1stQrt, Qtr 1, FirstQuarter

2. What is the difference between Dim and Public when used to declare
variables?

3. What is the permitted value range (approx.) of an Integer data type, could it be
used to store a salary value?
4. Explain basic differences between a MsgBox and an InputBox.

5. What is the difference between the keywords Let and Set and where can they
be used?

Notes

www.qa.com

Page 113
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Module 5 - Controlling Program Execution


This module demonstrates the use of VBA code to control how statements are
executed. You will learn various techniques that allow you to alter the flow of
code, and also to repeat code.
By the end of this module you will have covered:
 Understanding Control-of-Flow Structures
 Using the If...End If Decision Structures
 Using the Select Case ... End Select Structure
 Using the Do ... Loop Structure
 Using the For ... Next Structure
 Using the For Each ... Next Structure
 Guidelines for Use of Control-of-Flow Structures

Topic A - Understanding Control-of-Flow Structures


Each line of a Basic program is an individual step. Each line is part of a
procedure, and the collection of procedures makes up the code for the complete
program.

Sequential Execution
Normally, program steps are executed in sequence, beginning with the first line of
code at the top and moving down through until the bottom of the procedure is
reached. However, there are many cases where an alternative flow is needed,
and we shall next consider how this is achieved.

In this chapter you will take a look at various techniques supported by VBA to
construct non-sequential flows of execution. To do this you write statements
which make use of decision-making code, loops and subroutines.

Page 114
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Non-Sequential Execution
Two ways in which non-sequential execution is achieved:
1. Branching commands

Carry out operations only if certain conditions are detected. For instance use of
statements such as Call, Goto will redirect the running of code to another
location.

2. Looping commands

Automate step-and-repeat operations. For instance use of key statements such


as a do...loop, or a for...to...next loop will allow code to repeat itself.

Sequential Branching Looping

====== ====== ======


==== ==== ====
======== ======== ========
=== === ===
======== ======== ========
== == ==
Figure======
23 - Program flow examples ====== ======
======== ======== ========
========
Decision Making ======== ========
Decision making is a very common requirement both in real life and in the world
of computer programming. For example, a banking program might send a
message to a customer if that customer had an unauthorised overdraft.

All decision making situations have two things in common: something to test (the
condition) and something to do (the action). If, and only if, the condition is true,
then the action will be performed. If the condition is false, nothing may be done,
or a totally different set of actions can be executed.

Page 115
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic B - Using the If...End If Decision Structures


This is the most common and one of the ways to write decision making code.

Syntax
If condition Then
[Statements]
End If
The condition to test is placed between the If and Then keywords. The condition
must be an expression that evaluates to either a true or false result. If this
condition is found to be true, then the statement(s) between the Then and End If
will be executed. However if the expression evaluates to false, then all the
statements as far as End If are ignored. Statements after the End If are then
executed as normal sequential programming.

Condition
The condition part of an If ... Then ... End If statement can use a mixture of
variables, constants and arithmetic operators.

Comparison Operators
The list of comparison operators that can be used with IF statements.

Symbol Definition

= Equal to

<> Not equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

Comparisons are not restricted to numbers; string variables can be compared


with string constants or other string variables. For strings, comparisons such as x
> y are interpreted to mean 'x comes after y in alphabetic order'.

Page 116
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Logical Operators
More complicated conditional statements can be defined using the And and Or
keywords. An expression involving And is true if and only if both parts are true.
An expression with Or is true if one or both of its parts are true.

When using logical operators you can also use brackets to join tests together
evaluating multiple conditions for combinations of true or false. This is similar to
the logic Excel uses when nesting functions.

Example:
If NextTrainOnTime = True And DayofWeek = "Sunday" Then...
If (Dept = "HR" Or Dept = "IT") And PCMake = "Dell" Then...
If Not(DayOfWeek = 1) Then...
The list of logical operators that can be used with IF statements to allow multiple
tests.

Operator Definition

And Every expression must evaluate to True for the


condition to be True

Or Any of the expressions must evaluate to True for


the condition to be True

Not The opposite of the condition following, i.e.


reverse True to False

Topic C - Nested If Statements


An If...Then statement can contain many other VBA statements, including other
If...Then statements. This is called nesting, and is similar in logic to how Excel
allows IF Functions to be nested within each other.

VBA code which includes nested IF statements can be a little confusing to read. It
is always a good idea to lay out the program text in such a way that the program
becomes more obvious in meaning. One very common way of laying out the
program text is by using indentation. The contents of every If statement is
indented a fixed number of spaces from the left margin, and the level of

Page 117
QAVBA10INT v1.3 Introduction to VBA – Office 2010

indentation increases for each level of nesting. This makes it easier to see which
End If matches which If.

Example:
If CustomerBalance < 0 Then
If TimeOverdrawn >= 3 Then
MsgBox "You have been overdrawn for at least 3 days"
End If
End If

Indentation is generally used for any construction in VBA which can be nested; this
includes branching commands and various forms of loop. Most programmers like to
indent all of the code belonging to each procedure (Sub…End Sub) as well.
When indenting code, there are icons on the Edit toolbar, however use of the [Tab]
key will allow you to indent code.

The second If matches the first End If and forms a complete If...Then ...End If
statement in itself. This inner If is enclosed within the first If and last End If.

Now consider how the above statements will work. If the CustomerBalance is
greater than or equal to zero, the outer If statements condition is false and
nothing happens. If the CustomerBalance is less than zero, the outer If
statements condition is true and control passes to the first statement inside,
which is the inner If statement. The inner If statements condition is evaluated and
if the result is true – i.e. if TimeOverdrawn is at least 3 – then the MsgBox
statement is executed and a result will appear on the screen.

The Else Keyword


It is quite common to have two decision making statements which are mutually
exclusive; that is, the conditions in each being exactly the opposite.

Syntax
If condition Then
[Statements]
Else
[Statements]
End If

Page 118
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Example:
If CustomerBalance < 0 Then
MsgBox "You are in the red!"
Else
MsgBox "You are in the black!"
End If
This statement as opposed to the first IF..Then example will analyse the
expression and have both the True and False results evaluated. If the condition is
true, the first part (between Then and Else) is executed. If the condition is false,
the code between Else and End If is executed.

The ElseIf Keyword


If you need to check for more than 2 conditions, you can insert multiple ElseIf
statements into your If...End If block. It is used within an If statement as an
alternative to nested If statements.

You can have any (reasonable) number of ElseIf statements. They are tested in
the order in which you type them, so you can easily arrange a 'ladder of tests' to
give a predictable set of results.

Syntax
If condition Then
[Statements]
ElseIf condition Then
[Statements]
[ElseIf condition Then
[Statements]]
Else
[Statements]
End If
The condition being tested within each ElseIf may have no connection with the
original condition.

Page 119
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Example:
If NextTrainOnTime = True Then
MsgBox "The next train arrives on time!"
ElseIf Season = "Autumn" Then
MsgBox "The train delay is caused by leaves on the line"
ElseIf Season = "Winter" Then
MsgBox "The train delay is caused by compacted snow"
Else
MsgBox RandomExcuse()
End If
Once the test have evaluated to true, the whole If...End If code is completed and
the statements are executed below.

ElseIf is ONE WORD – the editor will not join 'else' and 'if' if you type them
separately, because it does not know if you intend to create another 'nested' if block.

Notes

www.qa.com

Page 120
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Using the If…End If Structure

Scenario
This activity will take you through the process of creating a basic If ... End If
structure to execute either of the two possible blocks of code. Then, a slightly
more advanced example with the Else statement being used.

Exercise
Before you start, close all open files and open the file called Test Data.xlsx.

1. Record a simple macro that alters cells G2 and then G3 with 2 different cell
FONT colours. Call the macro subFormatting. (recommend use a colour from
the Standard options, not the theme ones)
2. Once Recording has stopped, edit the macro in the VB Editor and rename the
module to modFormatting.
3. Save the files as Test Data.xlsm.
4. Alter your subformatting to appear much simpler(note your numbers will be
different or they could even be constants, it does not matter):
Sub subFormatting()
Selection.Font.Color = -16777024 'Burgandy
Selection.Font.Color = -4165632 'Dark Blue
End Sub
5. Add a comment with the colour you chose to the end of the lines.
6. Now add the following 3 lines around and within these statements:-
If ActiveCell < 150 Then
Selection.Font.Color = -16777024 'Burgandy
Else
Selection.Font.Color = -4165632 'Dark Blue
End If
7. Save the file.

Page 121
QAVBA10INT v1.3 Introduction to VBA – Office 2010

8. Split the screen, Run (or Step into) using various single cells within Column G.
9. Note the following labs will do the entire columns.
10. Add the following code to the Module.
Sub subLocation()
If ActiveCell < 1000 Then
ActiveCell.Offset(0, 1) = "UK"
ElseIf ActiveCell < 100000 Then
ActiveCell.Offset(0, 1) = "USA"
Else
ActiveCell.Offset(0, 1) = "Other"
End If
End Sub
11. Save the file.
12. Run this procedure on values within Column H.

13. In Excel you can Repeat the running of the macro easily by selecting the next
cell and then pressing [F4].

14. Step Into to observe which route the IF statements take you depending on the
cells value.
15. Save the file.

Page 122
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic D - Using the Select Case ... End Select Structure


The Select Case statement is an alternative to the If...ElseIf...Else...End If code,
and is useful in the cases where you do not need the full flexibility of ElseIf but
wish instead to consider various possible values of a single expression (often the
contents of a variable).

Syntax
Select Case testexpression
Case expressionlist-n
[statements-n]
[Case Else]
[Else statements]
End Select
Example:
Select Case DayOfWeek(datEndDate)
Case 0, 6
strDayType = "Weekend"
Case 1 To 5
strDayType = "WeekDay"
Case Else
strDayType = datEndDate & " is not a valid date"
End Select
Values for the Cases may be specified in various ways:
Case 2 individual value
Case 4, 6, 9, 11 individual values
Case 7 To 8 range of values (between)
Case Is > 11 one-sided range (greater or less than etc.)
Case Else none of the above
Case Else is the equivalent of Else in an If block. The End Select statement is
used to finish the structure, equivalent to End If. The Select Case can use
variables, dates or text values as well as numbers.

Page 123
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity – Using the Select Case…End Select

Scenario
We will continue to edit the previous activity file and now we require code that
format the Product line column, and divide their revenue into different formats.
Select case has been decided to be used instead of If statements.

Exercise
Before we start, confirm you have Test Data.xlsm open.

1. Record 4 different colours (use cells in Column F) in a macro called


subCases.
2. Edit the procedure to read as 4 simple Font lines such as this:
Sub subCases()
Selection.Font.Color = -4165632
Selection.Font.Color = -16776961
Selection.Font.Color = -11489280
Selection.Font.Color = -16727809
End Sub
3. Now add the select case cause around and within these statements.
Select Case ActiveCell.Offset(0, 1)
Case 0 To 150
Selection.Font.Color = -4165632
Case Is < 400
Selection.Font.Color = -16776961
Case 400 To 600
Selection.Font.Color = -11489280
Case Else
Selection.Font.Color = -16727809
End Select

Page 124
Introduction to VBA – Office 2010 QAVBA10INT v1.3

4. Save the file and test within Column F.

Topic E - Using the Do ... Loop Structure


We use Do … Loop construct for the code that has to be executed many times
and when we want the end-user to „decide‟ when to finish repeating the code.

Syntax
There are four variants of this structure:

1 Do Until condition 2 Do While condition


[statements] [statements]
[Exit Do] [Exit Do]
Loop Loop

3 Do 4 Do
[statements] [statements]
[Exit Do] [Exit Do]
Loop Until condition Loop While condition

The difference between the cases 1 & 3 and 2 & 4 is that the left column uses the
keyword Until before the condition, so the loop stops when the condition is true
(statements are executed while the condition is false). The right column uses the
keyword While before the condition, so the loop stops when the condition is false
(statements are executed while the condition is true).

The difference between the cases 1 & 2 and 3 & 4 is that cases 3 & 4 have the
condition on the Loop line which guaranties at least one execution of the loop.
The cases 1 and 2 have the testing on the Do line and that may mean that the
block isn't executed at all.

Example:
Do
strIn = InputBox("Enter value")
intVal = Val(strIn)
intTotal = intTotal + intVal
Loop Until strIn = ""

Page 125
QAVBA10INT v1.3 Introduction to VBA – Office 2010

If you forget to affect the condition with the statements between Do and Loop lines,
you will find yourself executing the endless loop.
The solution is to use {CTRL} + [Break] to stop the program.

Using Do ... Loop as a Counter


Sometimes we introduce a loop counter variable to control the number of times
we execute the same code. There is nothing special about such a variable; it is
simply used to keep track of the number of times the body of a loop will be
executed. This value is increased each time the program steps through the loop
body; when it reaches a predetermined limit, the looping stops.
Dim bytCount As Byte
Do While bytCount < 10
MsgBox 10 - bytCount & " times to go"
bytCount = bytCount + 1
Loop

In the above example, the first line creates a variable called bytCount and
initialises it to zero.

The Do statement here has the keyword While followed by a condition. The
condition is evaluated and, if it is true, the loop body is executed. If the condition
is false, the loop ends.
Using Do ... Loop to Interact with the End-User
In many applications, the program needs to ask a question of the end-user, and
make sure that the response is reasonable. For example, a program might ask
how old the end-user is, using code such as the one below.
Dim intAge As Integer
Do
intAge = Val(InputBox("Your age, please"))
Loop Until (intAge > 0 And intAge < 100)

However, if the end-user were to enter -43, or 500, these do not seem like
realistic values for an age of a person. The program should validate the input,

Page 126
Introduction to VBA – Office 2010 QAVBA10INT v1.3

and if the values do not seem reasonable, should ask again for some reasonable
values. If the end-user persists in entering strange values for the age, this
process could go on for some time. It is an ideal case for using a loop.

Activity – Using the Do…Loop Structure

Scenario
This activity will take you through the process of creating the Do ... Loop
structure to execute the block of code more than once. The aim is complete the
entire columns formatting routines from the previous labs. Although there are 4
versions of a Do Loop, we will use just one.

Exercise
Before we start, confirm you have Test Data.xlsm open.
1. Inset a module called modDoLoops.
2. Create a procedure called subDoLoops.
3. Write the following procedure in SubDoLoops:
Range("G1").Select
Do Until ActiveCell = ""
Call subFormatting
ActiveCell.Offset(1).Select
Loop
4. Save the file.
5. Copy and Paste the code again within the same procedure.
6. Alter the cell reference to H1 and the Call statement to Call subLocation
7. Copy and Paste the code again within the same procedure.
8. Alter the cell reference to 'F1' and the Call statement to Call subCases.
9. Save the file.
10. In Excel, run the macro subDoLoops.

Page 127
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic F - Using the For ... Next Structure


Loops that use counters are very common in programs. In order to make
programming them a little simpler, Visual Basic includes the For ... Next
construct.

Syntax
For counter = start To end [Step stepvalue]
[statements]
[Exit For]
[statements]
Next [counter]
Example:
Dim i as Byte
For i=1 To Sheets.Count
Sheets(i).Select
Range(“A1”).Select
Next i
Sheets(1).Select
This example code will select A1 in all the sheets of a file.

The keyword For is followed by a variable name (acting as a counter) and an


equals sign. After the equals sign is the start value for the variable and then the
keyword To followed by the end value. The end of the loop is marked by the Next
keyword. Each time around the loop, the variable is automatically incremented by
the step value (one is default) until it exceeds the ending value.

Using stepValue of -1, you can make the code do the loops in reverse order. Do not
forget to use higher value for startvalue.

Page 128
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Using the For…Next Structure

Scenario
This activity will take you through the process of creating the For ... Next
structure to execute the block of code more than once. The aim is to work with
column E the Product column from the previous activity file. The routine is going
to count the Number of rows and then alter the Fleet Maintenance records.

Exercise
Before we start, confirm you have Test Data.xlsm open.
1. Inset a module called modForNext.
2. Create a procedure called SubForNext, so it has the following statements:
Sub subForNext()
Dim intNoRows As Integer, intCounter As Integer
Range("A1").Select
Selection.CurrentRegion.Select
intNoRows = Selection.Rows.Count
For intCounter = 2 To intNoRows
If Cells(intCounter, 5) = "Fleet Maintenance" Then
Cells(intCounter, 5).Font.Color = -4165632
End If
Next intCounter
Cells(1, 1).Select
End Sub
3. Debug, Compile and if OK, Save the file.
4. In Excel, Run the code, is it quicker than the previous?
5. Remove ALL formatting from the current table. Delete column I.

Page 129
QAVBA10INT v1.3 Introduction to VBA – Office 2010

6. Add the following routine and run just once.


Sub MultiSheet()
Dim i As Byte
For i = 1 To 5
Sheets(i).Copy After:=Sheets(Sheets.Count)
Next i
End Sub

7. Save the file.

Topic G - Using the For Each ... Next Structure


For Each ... Next block is very similar to the normal For ... Next block, but the
loop counters place is taken by an object variable.

Syntax
For Each element In group
[statements]
[Exit For]
Next [element]
The effect of the code is to allow the program to step through all the elements of
a collection, you do not usually need to be concerned about the index number of
each element, but can instead concentrate on its properties.

The object being referenced within its collection is turned into a variable and used
as the loop counter. This variable also allows access to all the properties and
methods it relates to.

Example:
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
MsgBox ws.Name
Next ws

Page 130
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Using the For Each…Next Structure

Scenario
This activity will take you through the process of creating the For Each ... Next
structure that can be performed on individual elements within a collection.

The aim is to take the previous activity one stage further. And now process lots of
sheets.

Exercise
Before we start, confirm you have Test Data.xlsm open.
1. In the VB Editor, write the following procedure within the ModForNext module:
Sub AllSheets()
Dim ws As Worksheet
For Each ws In Worksheets
ws.Select
Call subDoLoops
Next ws
Sheets(ws).Select
End Sub

2. In ModDoLoops add Call SubForNext at the end of the existing procedure.

3. In Excel, work through each sheet and delete different blocks of entire rows.
E.g. Sheet 1 will have 1700+ rows, alter this for the other sheets.
4. Save the file before testing.
5. Run the Procure AllSheets.
6. Save and Close the file.

Page 131
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic H - Guidelines for Use of Control-of-Flow Structures

Modularisation
By breaking up a large program into smaller units, a program can be made a lot
easier to read, and therefore a lot easier to understand and easier to fix and
debug when it goes wrong. Another important reason for designing programs as
short procedures is that often a piece of code gets repeated at different stages in
the execution of the program. Because one procedure can „call‟ another, the code
can be shortened by removing the repeated sections.
In some cases, splitting the program up into units may enable the programmer to
spot bugs before they go into a production program. A program which is easy to
read should also be easy to maintain.

The process of splitting a long program into manageable fragments in this way is
known as modularisation.

Producing Maintainable Code


 Add comments

Apostrophe ( „ ) causes remainder of line to be ignored so you can enter an


explanation. You can also use a REM keyword. Your code will be displayed in
Green (unless changed in Options).
 Indent lines for legibility
VBA has several commands which have a block structure including If, Select, For
and Do, and it is helpful to indent all of the statements which fall within these
blocks, and to ensure that the statement which concludes the block starts at the
same position on the line as the statement which introduces the block.
 Break long lines

Sometimes the resulting lines are too long to fit on one line comfortably,
particularly if you wish to print the code, and VBA offers the extremely useful
option of splitting lines by typing a space follow by the underscore as the last
characters on a line.

Example:
MsgBox "This is the information which I am passing" _
& " to the procedure"

Page 132
Introduction to VBA – Office 2010 QAVBA10INT v1.3

It is not possible to split a line in the middle of a string within quotes; for this case,
you must split a string and then concatenate the remaining strings on subsequent
lines.

 Use meaningful names

Name your procedures, variables and constants so that you can easily recognise
them. E.g. CovertKilosToPounds, intDeptCode
 Use Intrinsic Constants

There are many constants that you can use to represent the values which would
be easier to understand when you check your code in the future.
MsgBox "The result is: " & vbNewLine & intResult
It is much easier to understand than:
MsgBox "The result is: " & Chr(10) & Chr(13) & intResult

Chr(10) and Chr(13) allow multiple lines in MsgBox and InputBox functions. The use
of vbCrLf could be considered as an alternative. Sending code Internationally could
cause Chr(10) or Chr(13) to display foreign characters such as è or á. VbCrLf is
more robust.

 Use argument names

Sometimes the methods can have the arguments of the same type and one can
get confused with which one is which and then the names of the arguments in
front of the value will make the clearer. It also makes the developers life easier by
not needing to enter extra comas to skip optional arguments.
MsgBox Prompt:= intResult, Title:= "Result"
Is the same as:
MsgBox intResult, , "Result"

Page 133
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Module 5: Review
This module was about:
 Understanding Control-of-Flow Structures
 Using the If...End If Decision Structures
 Using the Select Case ... End Select Structure
 Using the Do ... Loop Structure
 Using the For ... Next Structure
 Using the For Each ... Next Structure
 Guidelines for Use of Control-of-Flow Structures

Review Questions:
1. What is wrong with the following
If statement, IF bytAge =< 16 Then Call subError?
2. What prefix is used for a Double number, a Single number, and a Boolean
variable?
3. What does the DateSerial function allow you to do?

4. What bizarre measurement does an InputBox function use for its screen
position?
5. What helps to identify Excel, Word and VBA constants?

Notes

www.qa.com

Page 134
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Module 6 - Working with Forms and Controls


This module introduces you to working with VBA forms and their controls. You
will learn to create a form that in essence is a user defined message/input box
combined and can be used for greater interaction with users. VBA form design is
very similar in concepts and principles to Microsoft Access form design.
By the end of this module you will have covered:
 Understanding UserForms
 Creating a Form
 Displaying and Removing a Form
 Aligning and Sizing Controls
 Using the Toolbox
 Working with a Form‟s Properties, Methods and Events
 Working with Form and Control Properties, Methods and Events
 Setting the Tab Order
 Populating a Control

Topic A - Understanding UserForms

Introduction to User Forms


Customised user interfaces are implemented in VBA by means of standard
UserForms, which are supported most members of the Office suite (MS Access
is a notable exception). Forms in the VB Editor however have many similar
concepts to form design within MS Access.

Topic B - Creating a Form


To create a form, perform one of the following:
 Open the Insert menu and select the UserForm command.

 Left-click on Insert Userform icon ( ) on the Standard toolbar.

Page 135
QAVBA10INT v1.3 Introduction to VBA – Office 2010

This causes a new entry to be added to the hierarchy shown in the Project
Explorer window. Like modules, you could have many forms within your VB
Editor.

Figure 24 - User form

If you left-click on the grid while designing a form and Press [F5] you can see how
the form will appear in the application you are working with. You must close the form
down however to continue designing it.

The default name of a new form is UserForm1, UserForm2, etc. It is


recommended that you immediately rename each form (and any control which
you will place on it) as soon as you have created them. This is done by displaying
the Properties window and setting the (Name) property.

The most important reason for naming items immediately is that, if you double-click
on a control to create a block of code, it will assign whatever name currently applies
to the item; subsequently re-naming the item then detaches the code which remains
orphaned within the module.

Good practice is to assign all relevant controls a prefix that names the particular
type of control. Using this logic will help with the VB Editor. This is a logic that is
used within Access when creating Tables, Queries, Forms etc. When it comes to
writing VBA to refer to objects their prefix will help you to locate and understand
them quicker.

Page 136
Introduction to VBA – Office 2010 QAVBA10INT v1.3

The Me Object relates to the form you are working on. Entering Me. (include the
dot) within code will allow you to access all the objects quickly, hence naming
conventions will assist in code writing.

The following table are recommended naming prefixes for many of the common
objects you may use on a form.

Object Prefix Example

Form frm frmLogin

Label lbl lblSurname

Text Box tx txtSurname

Combo Box cbo cboDepartment

List Box lst lstPaymentType

Check Box chk chkIsMember

Option Button opt optFemale

Toggle Button tgb tgbActive

Frame fra fraGender

Command Button cmd cmdOk

Tab Strip through to Ref Edit are additional icons that maybe used on forms, these are
discussed on later pages.

The VBA keyword Me is used to reference the active (current) form, so:

Me.Width=400

is the shorter version of:

frmStartUp.Width=400

VBA code which responds to the events generated by the controls on a form is
stored in a module attached to that form.

Page 137
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Do not rename the event procedure after you renamed the control since the event
procedure stays attached to the old control name and your code will never execute.
Instead, create the same event procedure for renamed control, and move the code
to the new procedure.

Topic C - Displaying and Removing a Form

Displaying a Form
The form can be launched from within a procedure using the Show method.
frmSearch.Show

This is usually the only line of a macro (subroutine) that is then assigned to a
button on a QAT (Quick Access Toolbar) or a button on a sheet within Excel.

Removing a Form
If you only want to remove the form from the screen for a short period of time and
to return to it soon after, use the Hide method.
frmSearch.Hide

To return back to hidden form, use the Show method, the same statement you
use to launch the form for the first time. The hidden form retains all the changed
values.
To remove the form from the memory completely, use the following statement:
Unload Me

Using Show method after this statement will load the form with default values,
the changed values are lost when the form is unloaded.

The Hide method keeps the values of forms control, while the Unload removes
them from the memory.

Page 138
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic D - Aligning and Sizing Controls


You place the controls on your form by selecting the control in the Toolbox and
then either drag in the form to create a control of required size, or you just click
and let the VB Editor create a default sized control.
To select more than one control you can:

 Drag your mouse over controls in a lasso effect, although this method only
has to touch a control to include it.
 {SHIFT} + left-click on a control
 {CTRL} + left-click on a control
 {CTRL} + [A]

The VB Editor has some very useful facilities to help construction of forms. There
are many options on the Format menu, shown below, with which you can
instantly place buttons in the standard places on the form, or align sets of
controls.

VBA forms have a dedicated toolbar called UserForm this will show icons to allow
access to many of the Format commands shown below.

Figure 25 - Aligning dialog box

Once you have the controls on the form, you need to make the form look as good
as you can and as the end-user would expect them to look. Usually you start by

Page 139
QAVBA10INT v1.3 Introduction to VBA – Office 2010

making the size of the controls equal using Make Same Size command (either
the width, the height, or both), then you align the controls with Align command
(see Figure 25 for options) and finally you space them equally using Horizontal
or Vertical Spacing command.

When you select more than one control, one of them will have white „handles‟ in the
corners, while all the other controls will have them black. This indicates the
reference object – the one which will stay the same after your command. All other
controls will be based on the settings of this main control.

Topic E - Using the Toolbox


The Toolbox window shows all of the standard controls which are available for
inclusion on UserForms. These permit construction of interfaces which match the
current standard for E dialog boxes such as Format Cells etc.

Figure 26 - The toolbox toolbar

Notes

www.qa.com

Page 140
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Image Tool Description

Select Objects Selects, resizes or moves the existing controls.

Label Allows you to have text that you do not want the end-
user to change.

Text Box Holds text that the end-user can either enter or change.

Combo Box Allows you to draw a combination list box and text box.

List Box Use to display a list of items from which the end-user
can choose.

Check Box Use to display multiple choices when more than one
can be selected.

Option Button Use to display multiple choices from which the end-user
can choose one.

Toggle Button Creates a button that toggles on and off.

Frame Creates a graphical or functional grouping for controls

Command Button Creates a button the end-user can choose to carry out
a command.

Tab Strip through to Ref Edit are additional icons that maybe used on forms,
these discussed on following pages.

Labels are 'read only' as far as the end-user is concerned; they often describe
the adjacent control and their caption can have an Accelerator (short-cut key)
that can be used to jump directly to that control. Labels are also used for titles or
other text that is required on a form

TextBoxes provide the main facility for free text data entry. These can have
various properties set such as MultiLine for instance enabling a text box to be
used for comments.

Page 141
QAVBA10INT v1.3 Introduction to VBA – Office 2010

ComboBoxes and ListBoxes present lists of information. The distinction


between them is that the list box will allow more than one option (the MultiSelect
property), whereas the combo box only allows one row option to be selected.

CheckBoxes and OptionButtons are appropriate where a small number of


selections have to be made. The distinction between them is that any number of
check boxes in a frame may be selected, whereas selecting one option button
causes the others in the group to be switched off.

ToggleButtons are used where there is an on/off state to be represented.


Alternate use of the control pushes it in and pops it out.

Frames act as 'fences' for set of check boxes, option buttons or toggle buttons,
and their job is to isolate these sets from any other such controls on the same
form. They also give a good visual grouping of controls.

CommandButtons are used to trigger subroutines. These are commonly used


for OK and Cancel buttons.

TabStrip and MultiPage controls allow you to define multiple pages (tabs). If you
open Format Cells within Excel, the dialog box is a good example of a MultiPage
(the most common of these two controls).
ScrollBar controls work in the same way to Windows standard scroll bars.

SpinButton control is like a scroll bar with no middle section, and works in the
opposite direction, the upper button returns higher numbers. It is used to allow
end-users to increment or decrement values with the mouse click.
Image control displays a graphical image from your picture file.

RefEdit controls are used where the end-user has to select a range from an
Excel worksheet. The form can be collapsed while the selection is made.

Page 142
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Create a UserForm

Scenario
This activity will take you through the process of creating the UserForm.

The aim is to enable users with no knowledge of VBA to use macros through a
familiar user interface.

Exercise
Before you start, close any open file and start a new Excel file. Switch to the VB
Editor.
1. Insert a UserForm, by the end of this activity is should look like:

2. Change the (Name) property of the form to frmConversion and alter the
Caption property to Conversion.

3. Add all of the various controls as shown in the figure above. Alter their
Caption properties as required.
4. Save the file as an Excel Macro-Enabled workbook called Conversion.xlsm.

5. Insert a new Module, called modFormLoad. Create a new procedure called


subDisplayForm. Enter the following code:
frmConversion.show

Page 143
QAVBA10INT v1.3 Introduction to VBA – Office 2010

6. Go to Excel and add an icon to the QAT that will run the SubDisplayForm
procedure. Set it to be displayed only when this file is open (before you add
icon).
7. Save your file and test the loading of your form. Close the form.

Topic F - Working with a Form’s Properties, Methods and Events

Properties
The form, and each control you add have properties, like Access there are
hundreds of properties available to the developer. The list below has shows most
frequently used form properties:

Property Description

(name) It is important to Name your form, like you would


name a Sheet in Excel.

BackColor Sets the background colour of a form.

Caption The text that is displayed in the title bar of the


form.

Enabled If set to False, the end-user cannot interact with


the form by using the mouse, keystrokes,
accelerators, or hotkeys.

StartUpPosition Sets where the form will be displayed on the


screen.

Page 144
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Methods
Unlike properties, a form has few methods. The list below has names of some
frequently used form methods:

Method Description

Hide Hides the form, but keeps it in the memory.


Useful when you only temporary want to remove it
from the screen.

Show Displays the form that is either closed or hidden.

Events
There are many form events, the list below has names of some frequently used
form events:

Event Description

Activate Occurs when the form gets the focus. When the form is opened or when
the end-user returns back to the form from an object outside the form.

Deactivate Occurs when the form loses the focus. When the end-user hides or
closes the form, or when the end-user goes to an object outside the
form.

Initialize Occurs after the controls are loaded, so the programmer can set
dynamic initial values for controls.

To close the form and remove it from the memory use:

Unload Me
This code is placed within a Cancel or OK button when used on a Form.

Page 145
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic G - Working with Form and Control Properties, Methods


and Events
The property sheet for controls used on UserForms is extensive; fortunately most
controls have sensible defaults. Special properties of individual types of control
are covered on the next few pages; however, some useful properties are
common:

Enabled property determines whether or not the cursor is allowed to click within
a control (VBA uses the term focus i.e. the cursor with inside a control
(GotFocus), or leaving control (LostFocus).

Visible property determines whether or not the control appears – all controls are
shown in design mode regardless of this property setting.
The ForeColor and BackColor properties are useful in highlighting the active
control, and provide an alternative way of hiding information from the end-user.

The Tag property belongs to each control and the form itself; it is an extremely
useful as it allows you to make controls with separate grouped names, away from
the standard naming conventions already discussed.

Controls have only a few methods (Cut, Copy and Paste), a common one is
SetFocus which puts the cursor into the specified control. This can be useful
when the end-user is directed to correct an invalid entry.

Controls also provide a number of events – code can be attached to these events
that will run when the event occurs. Common events are Click (occurs when you
click on the control) and Change (occurs as the control value is being changed).
Some of the events differ unexpectedly between Microsoft products (e.g. Enter
and Exit events may be used in place of GotFocus and LostFocus).

Page 146
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Working with Form Controls


Control Properties
Although the list of properties of one control may be very different to the list of
another control, many share some attributes and behaviours. Here are details of
some frequently used properties:

Property Description

(Name) Unique name of a control. The default value of Name consists of the
objects class name followed by an integer. For example, TextBox1.

Accelerator A single character that the end-user can use to initiate the Click event.
Usually used with CommandButton, so that pressing the accelerator
key (with {ALT} held down]) will have the same effect as clicking on
the control. For Label, the cursor will jump to the next enabled control
following the label in the Tab Order.

Caption The text identifies or describes the object with which it is associated.
For CommandButton and Label, it specifies the text that appears in the
control. For Page and Tab controls, it specifies the text that appears
on the tab.

ControlTipText Enter text to be displayed in a screen tip that appears when you hover
over a control

Enabled The end-user cannot interact with the disabled control by using the
mouse, keystrokes, accelerators, or hotkeys.
A disabled control appears dimmed within the form.

Locked Specifies whether a control can be edited.

TabIndex Specifies the position of a single object in the tab order.


The index value of the first object in the tab order is zero.

TabStop Indicates whether an object can receive focus when the end-user tabs
to it.

Text Returns or sets the text in a TextBox. Changes the selected row in a
ComboBox or ListBox. For a TextBox, any value you assign to the
Text property is also assigned to the Value property.

Page 147
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Property Description

Value Specifies the state or the content of a control. For TextBox, the Value is
the same as the Text property. For CheckBox, OptionButton and
ToggleButton, an integer value indicates whether the item is selected.
For a CommandButton, setting the Value property to True in a
procedure initiates the button's Click event.

Visible Specifies whether an object is visible or hidden.

Although the end-user can‟t access a disabled control, it is still accessible through code.
When a control is Locked and Enabled, it can still initiate events and can still receive the
focus.

Details of some control specific properties:

Label Property Description

WordWrap If set to True, allows the caption to be displayed in more than one line.
Often used in conjunction with AutoSize property; which automatically
sizes the label to fit the caption.

TextBox Property Description

WordWrap If set to True, allows the caption to be displayed in more than one line.
Often used in conjunction with AutoSize property; which automatically
sizes the label to fit the caption.

MultiLine Causes the text box to accept newline characters so that an end-user
can type several lines of information.

EnterKeyBehaviour This will allow you to press Enter and not move to another control, but
to add a line.

PasswordChar Causes the specified character to be displayed in place of the actual


text typed by an end-user.
Normally this would be an asterisk.

ScrollBars Useful also when using MultiLine to allow scrolling.

Page 148
Introduction to VBA – Office 2010 QAVBA10INT v1.3

CommandButton Desciption
Property

Cancel When set to True, causes a button to respond to the [Esc] key being
pressed in the same way as if the end-user clicked on the command
button. (Cancel often has this set)

Default When set to True, causes a button to respond to the [Enter] key being
pressed in the same way as if the end-user clicked on it. (OK often has
this set)

Combo/ListBox Desciption
Property

ListRows Sets the number of rows that will be displayed in the list.
The other rows can be displayed using the scroll bars.

MatchRequired set to False, allows end-user to enter new value.

RowSource In Excel can be a Range of cells to populate the control.

Control Methods
Control have also methods, this table shows some methods available.

Method Description

AddItem Adds an item (for a single-column box) or a row (for a multicolumn list)
to the list. Used with ListBox, and ComboBox.

Clear Removes all objects from the list. Used with ListBox, and ComboBox.

RemoveItem Removes an item (for a single-column box) or a row (for a multicolumn


list) from the list. Used with ListBox, and ComboBox.

SetFocus Moves the focus to an object. Used with all controls that have Value
property.

Page 149
QAVBA10INT v1.3 Introduction to VBA – Office 2010

You cannot use the AddItem method and the RowSource property together. AddItem is
always written within a Forms Initialize event.

Control Events
As well as having different list of properties and list of methods, different controls
have different list of events to which they can respond. To easily access a
controls events, double-click on the control, from the VB Editor, select the
Procedure drop-down to select different events. Here are details of some
frequently used events:

Event Description

Click Occurs when the end-user clicks the mouse button while hovering over it.
Usually used with CommandButton, CheckBox, and OptionButton.

Double-click Occurs when the end-user double-clicks the mouse button within a
control.

Change Occurs when the end-user types the text in a control. Usually used with
TextBox, to check the input as the end-user types.

GotFocus Occurs when the end-user types the text in a control.

LostFocus Occurs when the end-user types the text in a control. Usually used with
TextBox, to check the value after the end-user input.

Page 150
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Managing your Controls

Scenario
This activity will continue where the previous left off. We will build our form up,
now concentrating on the controls previously added.

Exercise
1. Name all the controls as follows:-

2. fmeType – The frame at the top of the form


optIntoCm – The option button for in to cm
optCmtoIn – The other option button
lblInput and lblOutput for the two labels
txtInput and txtOutput for the two text boxes
cmdConvert and cmdExit for the two command buttons
3. Edit the following properties for various controls:

Control Property Setting

optIntoCm Accelerator I

optCmtoIn Accelerator C

optCmtoIn Value True

lblInput Accelerator n

lblOutput Accelerator u

txtOutput Enable False

cmdConvert Accelerator v

cmdConvert Default True

cmdConvert Enabled False

Page 151
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Control Property Setting

cmdExit Accelerator x

cmdExit Cancel True

4. Run the form from the VB Editor, note how Convert and Exit appear. Note you
can now use {ALT}+[accelerator] to move around the form (this may not work
on all controls, the next topic will resolve any issues).
5. Save the file.

Notes

www.qa.com

Page 152
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic H - Setting the Tab Order


When controls have been added to a form, it is important to consider the
sequence in which they will normally be visited as the end-user presses the [Tab]
key. The default order reflects the sequence in which you added the controls to
the form, and is unlikely to represent the required order.

The dialog box for setting the tab order is straight forward to use, provided that
you have named controls so that their identity is clear. You can activate the
dialog box, as shown in Figure 27, below selecting Tab Order command from
View menu. You then shift individual controls or blocks of controls up and down
the sequence, using the Move Up or Move Down buttons.

Figure 27 - Tab Order dialog box

If you have allocated accelerator keys to label controls you must ensure that the
appropriate control (e.g. TextBox) is next in sequence, since the labels pass the
focus to the next control in the tab order.

It is also important to consider the tab order within a Frame or MultiPage type
control as these have their own „internal‟ tab order away from the main form itself.
You can set the order in which these options are tabbed through. Right Mouse
Click within a Frame/Page and select Tab Order.

Each control on a form has its own TabStop and TabIndex property. The
TabStop property can be set to False, thus missing a control as a user tabs
though a form. The TabIndex property is linked to the Tab Order dialog list as
above.

Page 153
QAVBA10INT v1.3 Introduction to VBA – Office 2010

If a control has its TabIndex set to False, it can still be accessed by left-clicking
inside the control, however if the Enabled property is set to False then the control
is locked out totally.

Activity – Setting the Tab Order

Scenario
This activity will continue where the previous left off. We will build our form up,
now concentrating on the tabbing order of our form.

Exercise
1. Make sure you are in the Forms design screen.
2. Right-click just inside the forms FRAME control and select Tab Order.

3. Nothing should be altered unless you added/swapped the buttons around


from their obvious layout. Left-click OK.

4. Right-click inside the main form and select Tab Order alter the order so the
controls appear as follows:-

5. Note in the Properties window, the TabIndex and TabStop properties.


6. Edit the TabStop property of fmeType to False.
7. Run the form, note where the cursor initially appears, also test the tab order.

Page 154
Introduction to VBA – Office 2010 QAVBA10INT v1.3

8. Save the file.

Topic I - Populating a Control

Initialize Event of the UserForm


The UserForms Initialize event is an alternative method for pre-setting values in
various controls. It could be used to populate list/combo box entries, however
they also have a RowSource property in Excel, and if this is used, a drop-down
list cannot be populated within the Initialize event.

Example:
Private Sub UserForm_Initialize()
' Set default values for text boxes
Me.txtDate.Value = Format(Date, "dd/mm/yyyy")
Me.txtPassengers.Value = 1

' Set default option from the group


Me.optRail.Value = True

' Populate the list box with a code


With Me.lstOrigin
.AddItem "London"
.AddItem "Bristol"
.AddItem "Leeds"
End With

' Populate the combo box from an Excel Worksheet


Me.cboDestination.List = Range("Cities").Value
End Sub

The Textbox control does not offer any support for formatting, so in the example
above today's date is entered and specific display it created using the Format

Page 155
QAVBA10INT v1.3 Introduction to VBA – Office 2010

function. One option button from the group is checked and a combo box is filled
with the contents of a range in an Excel worksheet.

Adding Code to Controls


The controls placed on the form are capable of responding to various events and
that gives form its functionality. The most common event used on the form is a
buttons click event.

Example:
Private Sub cmdOK_Click()
' Validate entries and exit if acceptable
If cboDestination.ListIndex < 0 Then
MsgBox "Please select a destination"
cboDestination.SetFocus
Else
' Do something with the results
Call BookTicket(cboDestination.Value, optRail.Value)
End If
End Sub

The OK buttons Click event is the standard place to hold validation code,
because, on many forms, the end-user clicking this button is the only indication
that they have finished visiting other controls on the form. Notice how the
SetFocus method can be used to place the cursor in a specified control so that
its value may be modified.

Double-clicking on a control in the design screen will open the Code view and show
you the Click event procedure for that control. The same is true for the form.

The event procedures can be triggered, not only by the action of the end-user, but
also when a control value is changed by code. Failing to allow for this can lead to
unexpected effects, with event procedures being called when the form has not been
fully initialised.

Page 156
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity – Adding Code to the Controls

Scenario
This activity will continue where the previous left off. We will build our form up,
now concentrating on the code of our two command buttons and other controls.

Exercise
1. Make sure you are in the Forms design screen.
2. Double-click on the Exit command button. Enter the following code:
Unload me

3. Double-click back on the Form in the Project Explorer window.


4. Double-click on the Text box for input.
5. In the Change from the Procedure drop-down, enter the following code:
Me.cmdConvert.Enabled = True

6. Now select the Exit procedure for the txtInput control and enter:
If Me.txtInput = "" Then Me.cmdConvert.Enabled = False

7. Alter the Object to cmdConvert, and confirm it is the Click event. Enter:
If Me.optCmtoIn = True Then _
Me.txtOutput = Format(Me.txtInput * 0.3937008,
"#,##0.00")
If Me.optIntoCm = True Then _
Me.txtOutput = Format(Me.txtInput * 2.54,
"#,##0.00")

Page 157
QAVBA10INT v1.3 Introduction to VBA – Office 2010

8. In case someone enters text in the input box, add the following lines above
the previous code:
If Not (IsNumeric(Me.txtInput)) Then
Me.txtInput = ""
Exit Sub
End If

9. Save the form and test. Close file when finished.

Module 6: Review
This module was about:
 Understanding UserForms
 Creating a Form
 Displaying and Removing a Form
 Aligning and Sizing Controls
 Using the Toolbox
 Working with a Form‟s Properties, Methods and Events
 Working with Form and Control Properties, Methods and Events
 Setting the Tab Order
 Populating a Control

Review Questions:
1. What are the standard prefixes used for these objects: Label, ListBox, Frame
and Image?

2. What is important when considering the Accelerator property and the Tab
Order of labels and text boxes?
3. What statement is used to „close‟ a form and lose all the values on the form?

4. If you are going to use a TextBox for multiple lines of entry, what properties
might be considered to alter?

Page 158
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Module 7 - Debugging and Handling Errors


This module introduces you to the concepts of minimising errors that may occur
when running code. There are many ways of dealing with error trapping and, in
this module the theory behind error trapping is introduced.
By the end of this module you will have covered:
 Understanding Errors
 Using Debugging Tools
 Setting Breakpoints and Using Break Mode
 Stepping Through Code
 Trapping Errors with the On Error Statement
 Understanding the Err Object
 Working with Inline Error Handling
 Writing an Error-Handling Routine

Page 159
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic A - Understanding Errors

Opportunities for Misunderstanding!

Figure 28 - Project misunderstanding cartoon

This well-known cartoon first surfaced in the 1960s, and it is a reflection of IT


project management that it is as true today as it was then!

The cartoon shows that the end-user may just want something that works and is
fun to use but the various levels of „committee management' and 'programmer
implementation' may get in the way. It is often best to keep things simple and
easy to use.

Page 160
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Why Do Programs Have Errors?


 Guesswork Poor specification
 Changed requirements Resulting in unexpected side-effects
 Programming errors Happen to the best of us

 Complexity Leading to incorrect use or inappropriate


changes

 Poorly documented code Leads to misunderstandings and incorrect


changes

Types of VBA Errors


Many errors can and should be anticipated and error-handling code included in
your programs to limit the disruption which they cause; extensive testing with real
(or at least realistic) data is vital. Sometimes while recording a macro, or writing
code think about what could go wrong, and deal with the issues early rather than
when it is too late.

Error Types
There are three types of VBA errors and VBA handles them in different ways:
 Syntax errors

Syntax errors are mainly trapped at source by the VBA editor, as you try to move
the cursor off a particular line; some – such as omitting an End Sub – are picked
up as soon as you attempt to run any routine in a module (not just the routine
containing the error). It is also possible to locate syntax errors by using the
Debug menu option and then Compile Project command.
 Logic errors

Logic errors are possibly the most difficult to trace, because they result from code
which is legal but performs the wrong actions. You will need to review your code
and possibly enlist the help of the debugging aids to track down the source of the
problem.
 Run-time errors

Run-time errors are generally caused by the environment not being appropriate
for the action: perhaps an object has been named differently or the necessary
document is not open. Many such errors relate to your attempting to use
properties and methods which have not been expressed accurately.

Page 161
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Run-time errors must be handled by a program if execution is not to stop with the
standard error dialog on display to your end-users.

Topic B - Using Debugging Tools


Debugging facilities within the VB Editor environment are very supportive. Often
you will find it useful to run the code in single-step mode ([F8] from the keyboard),
or to set a breakpoint at a line in the code [F9]. Breakpoints are not saved with
the module but the Debug, Clear All Breakpoints command from the menu is
very useful once you have identified and solved a problem.

In the code window, when the program is in break mode, if you position the
mouse cursor over a variable, its value is displayed in a yellow box.

If you do require a breakpoint which is retained until explicitly removed (e.g.


between sessions of using a workbook or database), you can type the keyword
Stop.

In the VB Editor, there is a Toolbar that can be turned on Debug with relevant
commands on.

Immediate Window
The Immediate Window allows you to type single VBA commands which are
executed instantly: you can run procedures from here for testing (particularly
useful for testing procedures which need input arguments); you can also enquire
for the settings of most objects properties and change them.

You cannot declare new variables here, but you can utilise the names of existing, in-
scope variables. For instance, display values in message boxes.

You can display Immediate Window by doing any of the following:

 Clicking on an icon on the Debug toolbar


 Using keyboard shortcut {CTRL} + [G]
 Selecting View, Immediate Window command from the menu

Page 162
Introduction to VBA – Office 2010 QAVBA10INT v1.3

You can address this window from the with VBA code too. Making use of
Debug.Print code will allow you to pass values into the Immediate Window for
checking during/after procedures have run. This is very useful want to observe a
value of a particular variable as it changes while a code is executed.

The following columns shows examples of how to execute code within the
Immediate Window.

VBA/UDF Functions Subroutines Execute a statement

Print CmToIn(5.4321) Call ClearSheets() Sheets(1).Select

? CmToin(5.4321) Convert(5.5) Msgbox Sheets.Count

Debug.Print without an expression list gives a blank separator line. There are
additional commands for characters such as Tab that can be „sent‟ to the Immediate
Window.

The windows contents remain until the end of the programming session – you‟ll
need to select the text and press [Delete] key if you wish to clear the area
manually.

Locals Window
The Locals Window displays all declared variables‟ name, type and value from
the current procedure. You can also click on a value to change it. If you use the
Locals window, step through your code [F8] and note the changes as they
happen.
You can display Local Window by doing any of the following:

 Clicking on an icon on the Debug toolbar


 Selecting View, Locals Window command from the menu

Page 163
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Watch Window
The Watch Window can be used to monitor the value of a variable or expression,
or to stop execution of an otherwise free-running procedure when the value
changes or becomes True. If you use the Watch window, step through your code
[F8] and note the changes as they happen.
You can display Watch Window by doing any of the following:

 Clicking on an icon on the Debug toolbar


 Selecting View, Watch Window command from the menu
Watches can be added by doing any of the following:
 Selecting Debug, Add Watch command from the menu
 Right-click on a variable and select Add Watch...

Topic C - Setting Breakpoints and Using Break Mode

Breakpoints
A Breakpoint allows you to control where you would like to literally „break‟ into a
routine and control what happens next. This is achieved by clicking in the left
margin alongside your desired line (the grey margin) or by typing [F9] on the line
of code.
The coloured dot and highlight make it quite clear where such a breakpoint
exists. If a line of code is continued over multiple lines, this will be represented by
multiple dots, and highlights.

Don't forget to clear them before finishing a session of editing (on the menu bar
choose Debug, Clear All Breakpoints command)

Using Break Mode during Code Execution


If the error occurs during code execution, or if you have set a breakpoint in the
code, you will enter Break mode. When the Break mode is entered because of
the error in the code, the dialog box appears (see Figure 29 below) giving you the
option to either end the code execution or to debug the code.

Page 164
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Figure 29 - Debug Error Dialog Box

Choosing the second option (debug) will display the line of the code where the
execution had stopped.

When the program is in break mode, if you position the mouse pointer over a
variable, its value is displayed in a screen tip.

Topic D - Stepping Through Code


There are four commands on the Debug menu that deal with stepping through
the code. They are:

1. Step Into – [F8]

Executes code one statement at a time.

At design time, this command begins execution and enters break mode before
the first line of code is executed.

2. Step Over – {SHIFT} + [F8]

Executes code one statement at a time in a current procedure only.

The difference to Step Into command occurs when the current statement contains
a call to another procedure. The next statement displayed is the one in the
current procedure, not in the called procedure.

Page 165
QAVBA10INT v1.3 Introduction to VBA – Office 2010

3. Step Out – {SHIFT} + {CTRL} + [F8]

Executes the remaining lines of a procedure from the line where the cursor is.
All of the code between the current and the final execution points is executed.

4. Run to Cursor – {CTRL} + [F8]

Executes the lines of a procedure up to a line where the cursor is.


All of the code between the first and the current line is executed.

The fourth command for debugging on the Debug menu – Run to Cursor – is not
on the Debug toolbar. You might want to add it yourself using View, Toolbars,
Customize…

Notes

www.qa.com

Page 166
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Activity - Working with Debugging Steps

Scenario
This activity will confirm debugging actions already possibly undertaken, but also
to go over some others. Someone has spotted some incorrect formatting in a
procedure, rather than manually running each line we will use some new
techniques.

Exercise
Before you start, open the Test Data.xlsm and enable Macros.
1. With any sheet containing a table, select the table and set text colour to black.

2. Split the screen as previous between Excel and VB Editor. Left-click in the
Excel Window.
3. Press {ALT} + [F8], select the SubCases macro and then Edit.
4. Locate the Case Else line, and on the line below add a Breakpoint [F9].
5. Return to Excel again press {ALT} + [F8], this time select SubDoLoops.
6. Select Step Into and when in the VB Editor start using [F8].

7. Once you get inside subFormatting, note you will loop within it thousands of
times, so choose Step Out, however continued use of [F8] will bring you
straight back

8. Use Step Over, holding {SHIFT}+[F8], this time the code will still run but you
will be taken ‟over‟ the SubFormatting procedure. (it still runs)
9. Now in subDoLoops left-click on the statement that select F1 as a Range

10. Choose the Debug menu and Run to Cursor ( {CTRL}+[F8] ). Note what
happens.
11. Finally press [F5] to run the code to the end, does it though?
12. Alter the code to start all the macros in row 2 not row 1.
13. Save and Close the file.

Page 167
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Topic E - Trapping Errors with the On Error Statement


An error trap is set by an On Error GoTo label command, where the label is a
name placed at the start of a line and completed with an adjacent colon. Control
jumps to this point if the system detects any error, and the following code then
handles the problem and jumps to an appropriate place to continue execution.

On Error Resume Next statement may be used when an error is anticipated in


normal operation, and we just want to ignore it and continue with the code
execution. For instance you may have code that renames a sheet, however if the
sheet name may already exist rather than an error code can simple continue past
the line renaming a sheet.
After an error-handling routine is finished, we can resume the code execution
with one of these statements:
Resume execution resumes with the statement that caused the error.

Resume Next execution resumes with the statement immediately following


the
statement that caused the error.

Resume label execution resumes at the specified label. A label can be a


line
number too.

Once you set the error trapping, it will be executed on any error (even the one you
haven‟t anticipated!). If you want different solution for different errors, reset the error
trapping to VBA default with On Error GoTo 0 and then set another error trapping
before the next statement that may produce an error.

Topic F - Understanding the Err Object


VBA has an Err object which has properties that provide information about the
latest error which occurred. There are also a couple of methods for the Err object
as noted below.

Page 168
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Property Description

Number Returns the error number.

Description Provides the text of the error message which matches the number.

Source Contains the name of the element that generated the error.

Method Description

Clear Resets all of the Err objects to 0 (Zero) or “”.

Raise Generates a run-time error. You can force the error to test your code.

Use Raise method to test your error handling routines. Like this:
Err.Raise 11

Topic G - Working with Inline Error Handling


Inline error handling is when you place the code to handle errors directly into the
body of the procedure, rather that placing it at the end of the routine (local error
handler) or in a separate procedure (central error handler).

To enable this type of error handling you must enter On Error Resume Next
statement just above the line of the code that may cause an error and the code to
handle the errors immediately after it.
Sub OpenLogFile()
On Error Resume Next
Sheets(1).Name="Import Log" ' Rename the 1st Sheet
Sheets("Import Log").Select ' Select the Log sheet
End Sub

The example above renames the first sheet in my workbook to Import Log,
however this could have been done elsewhere/already named Import Log/maybe

Page 169
QAVBA10INT v1.3 Introduction to VBA – Office 2010

another sheet. Rather than VBA going through a whole routine to manage the
error (next example), the error is managed inlne and in effect ignored. If, however
there is no sheet called Import Log, then the first sheet is renamed.

Topic H - Writing an Error-Handling Routine

Local Error Handler


Local error handler is a code to handle errors placed at the
end of a routine. This is the most usual way of handling
errors within a procedure.
Sub MakeData()
On Error GoTo Trap
Kill "A:\Data.xls" ' delete existing file
...
TidyExit:
Exit Sub
Trap:
Select Case Err.Number
Case 71 ' disk not ready
MsgBox "Please put data disk in drive A"
Resume
Case 53 ' file not found
Resume Next
Case Else
Msgbox Err.Number & ": " & Err.Description
Resume TidyExit
End Select
End Sub

An error trap is set up at entry to the routine (generally the On Error GoTo
statement is the first executable statement in a procedure), and control diverts to
the specified labelled section if an error occurs. To avoid control dropping through

Page 170
Introduction to VBA – Office 2010 QAVBA10INT v1.3

to the handler when the routine completes normally, we have to add the Exit Sub
command before the error handler.

The error handler decides what action should be taken. If appropriate (for
example, if the error indicated no disk in a drive), Resume may be used, so that
the offending statement is re-tried. This can lead to infinite looping, so do take
care to provide some form of escape route!

Resume Next ignores the statement which failed, and continues from the next
one.

You can continue from another labelled point in the procedure, re-enabling error
handling by using Resume label.

If no continuation is sensible, the error handler can resume from another label at
which any tidying up can be done before leaving the procedure. Notice that it is
good practice to use the Resume ExitLabel form, rather than just dropping out of
the bottom of the procedure.

If an error occurs within a procedure which has no error handler in operation, or


within the error handler itself, the error will be passed back to the calling
procedure (if any) to deal with. If there are no active error handlers in any of the
active procedures then the standard VBA error dialog will appear.

If you want to avoid Visual Basic error messages completely you need to put
local error handlers in each procedure that can be called as a direct result of end-
user action.

Do not forget to add the Exit Sub command before the error handler to avoid control
dropping through to the handler when the routine completes without the error.
Remember code is executed sequentially.

Page 171
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Activity - Writing an Error Handling Routine

Scenario
This activity will complete the course by showing how to construct an error
handling routine that can be placed within most other procedures. First we will
see the difference between Function error handling and Macro handling. Then go
onto write a trapping routine for known errors.

Exercise
Before you start, open the Error Trapping.xlsm and enable Macros.

1. With the file open, in either A2 or B2 enter the following:


A negative number, A large number >1000, a text value or nothing at all.
2. Note we never get a debug, simply the function cannot understand the Value
or Number being entered. Put sensible numbers into both shaded cells.

3. Now display the VB Editor, and inside SubDivide Run the routine, a message
box displaying the answer should appear.

4. Split the screen and enter a negative number into B2. When you run
SubDivide, note the error message and its number.

5. Alter the code as follows (bolder lines are new) so you get your own
customised error message without the Debug/End option:

Page 172
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Sub subDivide()
On Error GoTo errTrap
Dim myNumber As Byte, myDivisor As Byte
myNumber = Range("A2").Value
myDivisor = Range("B2").Value
MsgBox "Answer is " & myNumber / myDivisor
Exit Sub
errTrap:
MsgBox Err.Number & vbNewLine & Err.Description
End Sub

6. Save the file and test the code.

7. Now to extend the code to allow for this and other potential errors, alter the
code further to be:
errTrap:
If Err.Number = 6 Then
MsgBox "Negative numbers not allowed"
Exit Sub
Else
MsgBox Err.Number & vbNewLine & Err.Description
End If

8. Save and test the code


9. What is the error number for large numbers?
10. Alter the message to say, Invalid amount, not negative numbers.
11. Enter in B2, word. What is the error number now found?
12. Above the Else add the following code:
ElseIf Err.Number = 13 Then
MsgBox "Please enter numbers not text"
Exit Sub

Page 173
QAVBA10INT v1.3 Introduction to VBA – Office 2010

13. Test again, finally enter a 0 (Zero) into B2, note the new error number
14. This time enter the following ElseIf, above the Else statement:
ElseIf Err.Number = 11 Then
MsgBox "Zero not allowed, set to 1"
Range("B2").Value = 1
myDivisor = 1
Resume

15. Save and Test


16. Save and Close the file.

Module 7: Review
This module was about:
 Understanding Errors
 Using Debugging Tools
 Setting Breakpoints and Using Break Mode
 Stepping Through Code
 Trapping Errors with the On Error Statement
 Understanding the Err Object
 Working with Inline Error Handling
 Writing an Error-Handling Routine

Review Questions:
1. Why could a line of code go red when typing in VBA?
2. Name some keyboard commands for use when Debugging?
3. Name the various Step commands?
4. What does error number 1004 relate to?

Page 174
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Notes

www.qa.com

Page 175
QAVBA10INT v1.3 Introduction to VBA – Office 2010

Review Questions Answers

Module 1
1. If you display the developer tab, which other Office applications also display
the Developer Tab?
 Microsoft Word, Outlook and PowerPoint
2. Where is the only place you can rename a macro?
 In the VB Editor

3. When you type Sub MacroName and press enter What will automatically
happen within the VB Editor?

 Brackets are added, End Sub is added, and keywords are turned
blue
4. What is the file extension for a Word 2010 file containing a Macro?
 DOCM

5. When using help, which keyboard command can take you straight to the
relevant help section?
 [F1]

Topic C Activity Review Question:


 You are in the finance industry and use a format for negative numbers in red
and brackets. Where can you store a Macro so it would be available for every
Excel file you open?
 Personal Macro Workbook

Topic D Activity Review Question:


 Discuss the following. What could make this macro go wrong?

 Blank Cells when using Ctrl Down, cells outside the table where
there are blank rows/columns, using the mouse to select cells and
therefore not selecting a table but a range of cells that could alter.

Page 176
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic E Activity Review Question:


 What do you think Word will do to a file called DOCX if there is a macro saved
within it?
 DOCM

Module 2
1. How many modules/procedures can you have within the VBA environment?
 Unlimited
2. Which area of your module do the words Option Explicit appear?
 General Declarations (the top of a module)
3. What is wrong with this line of code?
Function myAge (Optional DOB As Date, AgeNow As Byte) As
Byte
 Optional arguments should be last within the brackets of the
function
4. Can you place multiple Call statements together within a module?
 Yes
5. What code will stop a macro immediately?
Exit Sub
Topic J Activity Review Question:
 Why did AddFullName2 still produce the result even though there was an
occasional error message?

 The Optional argument had a „default‟ value so when blank a value


was used.

Module 3
1. Name an Object within Excel we have not yet come across?
 Answers will vary, e.g. Chart, Pivot Tables
2. How is it easy to identify a collection?
 The object is plural

Page 177
QAVBA10INT v1.3 Introduction to VBA – Office 2010

3. What keyboard command opens the Object Browser?


 [F2]
4. What symbol dictates a Method and a Property?
 Method – flying rubber, Property a finger pointing over a small sheet
5. If using a With statement what must be used to complete the syntax?
End With

Topic H Activity Review Question:


 Name some other properties that are Boolean and therefore can be toggled
on and off?

 Too many to list hear, but anything that can be on/off, check all
icons on ribbon, and all options available for application.

Module 4
1. Of these variable names which would be valid?
 FirstQuarter
2. What is the difference between Dim and Public when used to declare
variables?
 The scope of the variable to be declared (when it is in memory)
3. What is the permitted range (approx.) of and Integer data type, could it be
used to store a salary value?
 +/- 32,000 (approx) so not appropriate for Salary
4. Explain basic differences between a MsgBox and an InputBox.
 MsgBox will display a message (and accept multiple buttons as an
interface), an InputBox accepts values to be entered.

5. What is the difference between the keywords Let and Set and where can they
be used?

 Let is optional, used with variables. Set is used if the variable is an


Object and not simply a value.

Page 178
Introduction to VBA – Office 2010 QAVBA10INT v1.3

Topic I Activity Review Question:


 What does the value 273 equate to in a message box
 OK, Cancel buttons, Critical Symbol, Default Button 2

Module 5
1. What is wrong with the following If statement?
If bytAge =< 16 Then Call subError
 The comparison should be <=

2. What prefix is used for a Double number, a Single number, and a Boolean
variable?
 dbl, sng, bln

3. What does the DateSerial function allow you to do?

 Converts a Year number, Month number and Day number into a


date.

4. What bizarre measurement does an InputBox function use for its screen
position?
 A TWIP (20th of an Imperial Point)
5. What helps to identify Excel, Word and VBA constants?
 A two letter prefix, xl, wd or vb.

Module 6
1. What are the standard prefixes used for these objects: Label, ListBox, Frame
and Image?
 lbl, lst, fme and img
2. What is important when considering the Accelerator property and the Tab
Order of labels and text boxes?
 The label is in the tab order preceding the control
3. What statement is used to „close‟ a form and lose all the values on the form?
frmname.Close

Page 179
QAVBA10INT v1.3 Introduction to VBA – Office 2010

4. If you are going to use a TextBox for multiple lines of entry, what properties
might be considered to alter?
 EnterKeyBehaviour, MultiLine and ScrollBars

Module 7
1. Why could a line of code go red when typing in VBA?
 Syntax Error
2. Name some keyboard commands for use when Debugging?
 Commands using [F8] or [F9] (with {SHIFT} etc.)
3. Name the various Step commands?
 Step Into, Step Over, Step Out
4. What does error number 1004 relate to?
 Run Time Error, lots of reasons

Notes

www.qa.com

Page 180

You might also like