VBA Training 2
VBA Training 2
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.
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
Page ii
Introduction to VBA – Office 2010 QAVBA10INT v1.3
List of Figures
Page iii
QAVBA10INT v1.3 Introduction to VBA – Office 2010
Page iv
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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
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
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.
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.
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.
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.
Page 4
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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.
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.
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.
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
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.
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
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
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
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).
Notes
www.qa.com
Page 12
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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
Keyboard Shortcuts
One way to run your macro manually is to nominate a shortcut within the recorder
start-up dialog box, as shown here.
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
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.
Page 15
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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
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.
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
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
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.)
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
Notes
www.qa.com
Page 20
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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.
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.
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
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.
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.
The Edit toolbar (shown above) is not displayed by default. Right-click on the
Standard toolbar and select Edit.
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
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 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
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.
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
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.
Shortcut Action
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
Within the VB Editor there is a help box in the upper right corner of the screen
where developers can enter search words.
Page 28
Introduction to VBA – Office 2010 QAVBA10INT v1.3
Notes
www.qa.com
Page 29
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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
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
Page 32
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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.
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
Left-click down arrow next to the icon on the Standard toolbar and
select Module.
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.
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
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.
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.
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
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.
Page 37
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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
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
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.
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
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
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.
Notes
www.qa.com
Page 43
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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.
Page 44
Introduction to VBA – Office 2010 QAVBA10INT v1.3
0 “” Nothing
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
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
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!
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:
Notes
www.qa.com
Page 48
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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?
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?
Page 50
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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
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.
Range object Controls how you can access a cell or manipulate a range of cells.
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.
Page 53
QAVBA10INT v1.3 Introduction to VBA – Office 2010
Page 54
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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
Notes
www.qa.com
Page 56
Introduction to VBA – Office 2010 QAVBA10INT v1.3
Notes
www.qa.com
Page 57
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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.
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
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
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.
Page 59
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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
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
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.
Syntax
With object
[Statements]
End With
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
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
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
Type Value
Number 23
Text “London”
Variable intPrice
Calculation intPrice*1.2
Object.Property txtPrice.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
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
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)
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
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
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
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
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.
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
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
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
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
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!
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
+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer division
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
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
Page 80
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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:-
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.
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
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
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.
The type is required so that VBA knows the kind of data which is to be stored in
the variable.
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.
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
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
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
1. Locals Window
3. Watch Window
More about Locals, Immediate and Watch Windows, see notes on the Debugging
and Error handling module.
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
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
Page 90
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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.
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
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("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
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.
Page 98
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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
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.
Syntax
As a function:
MsgBox(prompt[, buttons] [, title] [, helpfile, context])
Page 100
Introduction to VBA – Office 2010 QAVBA10INT v1.3
Argument Definition
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!”
Page 101
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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).
0 vbOKOnly
1 vbOKCancel
2 vbAbortRetryIgnore
3 vbYesNoCancel
4 vbYesNo
5 vbRetryCancel
16384 vbMsgBoxHelpButton
Page 102
Introduction to VBA – Office 2010 QAVBA10INT v1.3
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
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.
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.
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).
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7
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
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
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)?
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.
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
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.
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
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
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
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
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
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
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
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
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.
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.
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
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
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
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.
Page 124
Introduction to VBA – Office 2010 QAVBA10INT v1.3
Syntax
There are four variants of this structure:
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.
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.
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
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.
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
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
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
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
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
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.
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.
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.
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
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.
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 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.
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
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.
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
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.
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.
Notes
www.qa.com
Page 140
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
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
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.
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
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.
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.
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
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
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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
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:-
optIntoCm Accelerator I
optCmtoIn Accelerator C
lblInput Accelerator n
lblOutput Accelerator u
cmdConvert Accelerator v
Page 151
QAVBA10INT v1.3 Introduction to VBA – Office 2010
cmdExit Accelerator x
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
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.
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.
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.
4. Right-click inside the main form and select Tab Order alter the order so the
controls appear as follows:-
Page 154
Introduction to VBA – Office 2010 QAVBA10INT v1.3
Example:
Private Sub UserForm_Initialize()
' Set default values for text boxes
Me.txtDate.Value = Format(Date, "dd/mm/yyyy")
Me.txtPassengers.Value = 1
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.
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
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
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
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
Page 159
QAVBA10INT v1.3 Introduction to VBA – Office 2010
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
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.
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.
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.
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.
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:
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:
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)
Page 164
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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.
At design time, this command begins execution and enters break mode before
the first line of code is executed.
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
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.
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
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
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.
Page 168
Introduction to VBA – Office 2010 QAVBA10INT v1.3
Property Description
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
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
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.
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 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
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.
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
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
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
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
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]
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
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?
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
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?
Page 178
Introduction to VBA – Office 2010 QAVBA10INT v1.3
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
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