Professional Documents
Culture Documents
Microsoft Excel Introduction To Visual Basic For Applications (VBA) Student Edition
Microsoft Excel Introduction To Visual Basic For Applications (VBA) Student Edition
Microsoft Excel
VBA Programming Introduction
Student Edition
MicrosoftExcel
IntroductiontoVisualBasicfor
Applications(VBA)
StudentEdition
FORCOURSEBOOKINGSANDGENERALENQUIRIES
LONDON (020) 7417 0880
Copyright 2008 by Key Training Solutions Ltd. All rights reserved. Information in this document is
subject to change without notice and does not represent a commitment on the part of Key Training
Solutions Ltd.
Trademarked names appear throughout this book. Rather than list the names and entities that own the
trademarks or insert a trademark symbol with each mention of the trademark name, Key Training
Solutions Ltd states that it is using the names for editorial purposes and to the benefit of the trademark
owner with no intention of infringing upon the trademark.
DISCLAIMER
Key Training Solutions Ltd has taken every effort to ensure the accuracy of this manual. If you should
discover any discrepancies, please notify us immediately.
IMPORTANT NOTE
Unless otherwise stated, screenshots of dialog boxes and screens in this lesson were taken
using Excel 2003 running on Window XP Professional. There may, therefore, be minor
cosmetic differences if you are using Excel 2000 or 2002(XP), or if you are running on
Windows 2000 or Windows Vista.
Concepts, discussions, procedures and functionality, however, remain unchanged.
Page 2
Contents
ABOUT KEY TRAINING SOLUTIONS LTD .................................................................................................. 2
COPYRIGHT & TRADEMARKS...................................................................................................................... 2
DISCLAIMER ...................................................................................................................................................... 2
IMPORTANT NOTE ........................................................................................................................................... 2
LESSON 1 - RECORDING MACROS .............................................................................................................. 5
WORKING WITH VISUAL BASIC FOR APPLICATIONS ........................................................................................... 6
DEFINING MACROS ............................................................................................................................................. 6
RECORDING A MACRO ........................................................................................................................................ 6
RUNNING A MACRO .......................................................................................................................................... 10
RECORDING A MACRO USING RELATIVE REFERENCES..................................................................................... 11
SAVING A WORKBOOK CONTAINING A MACRO ................................................................................................ 12
OPENING A WORKBOOK CONTAINING A MACRO .............................................................................................. 13
SAVING THE PERSONAL MACRO WORKBOOK ................................................................................................... 17
Exercise........................................................................................................................................................ 18
Recording Macros ..................................................................................................................................................... 18
Contents
Page 4
DEFINING MACROS
Discussion
A macro is a small program that you can use to perform frequently used simple
operations automatically, or for more complex tasks that require consistency. It
contains all the commands and actions necessary to complete a task.
Excel macros are written in the VBA programming language. The series of commands
used in a macro are known as a procedure. Each procedure is given a name that is used
to identify the macro for later execution (running) and editing.
Each procedure is saved in a device called a module. In Excel, this module is attached
to the worksheet in which the macro was written. Since Office 97, a module cannot be
seen in the normal Excel window because it is hidden. You must use the Visual Basic
Editor to select a module and view, write or edit the macro code.
In order for a macro to run, the Excel file containing the VBA code must be open.
RECORDING A MACRO
Discussion
A macro can be created using the macro recorder. You perform the steps you want to
include in the macro and Excel records them into a macro procedure. The steps you
perform are translated into VBA, which uses macro statements to replace your steps.
Page 6
When you record a macro, Excel creates a module that is attached to a worksheet. A
module can contain more than one macro.
At the start of the macro recording process, you enter the following information into
the Record Macro dialog box:
Macro name:
Shortcut key:
Type a letter that you wish to use in conjunction with the CTRL
key to run the macro later. For example, if you press x you can
later run the macro using CTRL x.
Tip: Most of the CTRL <something> keystrokes are already used
by Excel for other commands (eg. CTRL o for File Open, CTRL c
for Copy). To avoid the macro keystroke overriding the
standard Excel command, combine the SHIFT key with the
keystroke. For example, by entering SHIFT O into the Shortcut
key: box, the macro will run using CTRL SHIFT O, thus
avoiding normal Excel keystrokes.
Select the location where you want the macro recorder to store
the VBA code for the macro.
The code can be stored in the Personal Macro Workbook, a New
Workbook or This Workbook.
The Personal Macro Workbook is a special Excel file that Excel
creates for you the first time that you record a macro in it. Excel
names this file personal.xls and stores it in a folder named
XLSTART. The XLSTART folder forms part of your personal
settings (profile) so should always be available at any computer
that you log on to and which is connected to your corporate
network.
Excel manages personal.xls by automatically saving it when you
exit Excel, and automatically opening it when you launch Excel.
As a result, any macros in the Personal Macro Workbook should
always available for you to use.
The Personal Macro Workbook is the ideal place, therefore, to
store general purpose macros that you may want to use on ANY
Excel file.
Recording a macro in This Workbook is more usual in cases
where the macro is specific to that workbook only. For example,
a macro that carries out an analysis explicit to a table that is
found in that workbook only.
Storing a macro in This Workbook also makes it more available
and transportable in shared situations. For example, if you send
the workbook as an attachment, the macro will also be available
to the recipient. If you had stored the same macro in the
Page 7
Page 8
9. Perform the actions that you wish the macro to repeat later.
10. Click the Stop button
when finished.
NB If you do not see the Stop Recording toolbar, you can stop
the macro by clicking Tools - Macro- Stop Recording.
9. Perform the actions that you wish the macro to repeat later.
10. Click the Stop button in the status bar when finished, or
Page 9
RUNNING A MACRO
Discussion
Macros are saved in modules with the workbooks in which they were written. Before
you can run a macro, the workbook with the module containing the macro must be
opened. When you select a macro name in the Run Macro dialog box, Excel performs
the commands listed under the macro name in the module in sequence.
Macros in any open workbook can be run from any other open workbook.
Page 10
on the Stop
on the Stop
Page 11
Page 12
workbook, you will not be able to, and a message will appear explaining how to save it
correctly.
Page 13
In Excel 2000 03 you are warned about opening a workbook that contains macros by
means of message boxes. Examples of these are shown below:
In Excel 2007, you are warned about opening a workbook that contains macros by
means of a Notification in the Message Bar.
Page 14
Upon clicking the Options... button in the message bar, you are presents with a
window offering choices on how to deal with the macro(s) contained in the workbook
that you are trying to open. Examples are:
Page 15
The workbook contains macros but they are digitally signed from a
trusted source
Page 16
Page 17
EXERCISE
RECORDING MACROS
1. Open a blank workbook.
2. Record a macro with absolute references as follows:
Name: MyDataEntry
Keystroke: Ctrl-Shift-R
3. The macro should first add a new sheet to the workbook and then starting in cell A1,
enter the data and formatting shown below.
Bold
Italic
4. Run the MyDataEntry macro using the assigned keystroke. Note how the data is
entered into the same cells as when recorded.
5. Save the file as Sales Record and close.
6. Open the file Tables.
7. Select cell A1 on the Central Region sheet.
8. Record a macro with relative references as follows:
Name: FormatHeading
Keystroke: Ctrl-Shift-H
Page 18
Page 19
LESSON 2
THE VISUAL BASIC EDITOR
In this lesson, you will learn how to:
Launch the Visual Basic Editor
Navigate the VB Editor screen
Find a macro in the VB Editor
Insert a module sheet into an Excel workbook
Copy a module sheet between workbooks
Rename a module sheet
Delete a module sheet
Menus and Toolbar(s) provide methods for giving commands to the editor.
The Project Explorer pane shows all open Excel workbooks files and Add-Ins.
Primarily used for locating files and accessing locations where VBA code is
stored. ).
The Properties pane primarily used for adding additional characteristics and
settings to objects on User Forms and/or for naming module sheets. ).
The Code Pane primarily a simple word-processor used for writing and editing
the VBA code on a selected module sheet).
Menus and
Toolbar
Project
Explorer
Code
Pane
Properties
Pane
on the VB Editor
Page 22
The Project Explorer pane shows at the top level (in bold) all the open Excel files. They
are normally listed as: VBAProject (file name).
Page 23
Page 24
Page 25
Page 26
Page 27
EXERCISE
USING THE VB EDITOR
1. Close any open files.
2. Open the files, Data Records and Sales Analysis. Enable
macros, if prompted.
3. Launch the VB Editor.
4. Insert a module sheet into the Data Records workbook.
5. Rename the module sheet to FormattingMacros.
6. Open Module1 in the Sales Analysis workbook.
7. Copy the FormatTable macro.
8. Paste it into the FormattingMacros module of Data Records.
9. Return to Excel.
10. Save and close Data Records and Sales Analysis.
11. Open the file, Special Macros. Enable the macros, if prompted.
12. Launch the VB Editor.
13. Export the GeneralMacros1 module sheet as a file named
GeneralMacros.txt.
14. Import the GeneralMacros1.txt file to the Personal Macro
Workbook (personal.xls).
15. Remove the GeneralMacros1 module from the Special Macros
workbook. Do not export it.
16. Move the GeneralMacros2 module sheet from Special Macros
to the Personal Macro Worksheet by clicking and dragging it.
17. Close the VB Editor.
18. Exit Excel and save the Personal Macro Worksheet.
Page 28
Page 30
29. Select the name of the macro to which you want to assign the
shortcut key.
30. Click Options.
31. Type a letter (preferably in conjunction with the SHIFT key).
32. Click OK.
33. Click the Close button in the Macro dialog box.
Procedures
1. Open the workbook containing the macro(s). If the macros are
in the personal macro workbook, it will already be open.
34. Click Tools.
35. Select the Customize... command.
36. Open the Commands tab.
37. Select Macro from the Categories list box.
38. Drag the Custom Button
location on one of your existing toolbars.
to a convenient
Page 31
39. Right-click the custom button that you have added to your
.
toolbar and type a descriptive name for it
This name will be used as the Help Tip when you later point
at the button to use it.
40. Select Change Button Image or Edit Button Image...
to modify the appearance of the button, if
necessary.
41. Right-click the custom button and select Assign Macro...
.
42. Select the macro to assign to the custom button.
43. Click OK.
44. Click Close in the Customize dialog box.
Procedures
1. Open the workbook containing the macro(s). If the macros are
in the personal macro workbook, it should already be open.
Page 32
Procedures
1. Open the workbook containing the macro(s). If the macros are
in the personal macro workbook, it will already be open.
45. Click Tools.
Page 33
Procedures
1. Open the workbook containing the macro(s). If the macros are
in the personal macro workbook, it will already be open.
53. Enable the macros, if necessary.
54. Click Tools.
55. Select the Customize... command.
56. Select the Commands tab.
57. Select Macros from the Categories list box.
Page 34
item
62. Right-click the custom menu item and select Assign Macro...
.
63. Select the macro to assign to the menu item.
64. Click OK.
65. Click Close in the Customize dialog box.
Procedures
1. Open the workbook containing the macro(s). If the macros are
in the personal macro workbook, it will already be open.
66. Click Tools.
67. Select the Customize... command.
68. Open the Commands tab.
69. Select New Menu in the Categories list box.
70. Click and drag New Menu from the commands list box at
to a convenient position on the
the right
menu bar (eg. between Window and Help).
71. Release the mouse button.
Key Training Solutions Limited
Page 35
72. Right-click the new menu and type a descriptive name for the
menu in the Name: box (eg. Macros).
Tip: Type an ampersand (&) immediately before the character
that you want to underline and make the shortcut key for the
.
menu
73. Add custom menu items to the new toolbar as described on
page 34.
Custom menu items that you may have already added to
existing menus can also be moved (click and drag) to the new
menu. The Customize... window MUST be open in order to do
this, even if you are not doing anything inside it.
74. Click Close in the Customize dialog box when finished.
Procedures
1. Click the Tools menu.
2. Select the Customize... command.
3. Right-click the toolbar button that you want to delete.
4. Select Delete.
5. Click the menu containing the macro you want to delete.
6. Right-click the menu item that you want to delete.
7. Select Delete.
8. Click Close in the Customize... window.
Page 36
Page 37
78. Open the worksheet that you want to create the macro button
on.
79. Click the View menu.
80. Point at Toolbars.
81. Select Forms from the side menu.
82. Click the Button button
Page 38
Page 39
101.
102.
103.
Page 40
Page 41
105.
106.
107.
Page 42
EXERCISE
ASSIGNING MACROS
1. Open the file Run Macros. Enable the macros, if prompted.
This workbook contains several macros that apply different
number styles.
2. On the Qtr 1 sheet of the workbook, assign all the macros
stored in the workbook to worksheet buttons (use the Forms
toolbar). The picture below gives you a guide to what is
required.
3. Select the range C4:F9 and run the SterlingStyle macro using
the worksheet button.
4. Select the range C14:F19 and run the PlainStyle macro using
the worksheet button.
5. On the same range, run the NumberStyle macro using the
worksheet button.
6. Select the ranges C3:E3 and C13:E13 and run the DateStyle
macro using the worksheet button.
7. Assign the macros in this workbook to keystrokes as follows:
Page 43
Page 44
LESSON 4
WRITING PROCEDURES
In this lesson, you will learn how to:
Understand the difference between Objects, Methods and Properties
Write basic VBA statements in a procedure
Deal with a Run-Time error
Work with the Object Browser
Refers to
Application
Workbooks
A collection of all the Workbooks that are currently open in the Excel
application.
Page 46
Worksheets
Range
Discussion
Collections
You will notice that a couple of the objects in the above list are plural (viz. Workbooks
and Worksheets). This is because they are collections and when used, apply
whichever method that follows to ALL the open objects that they refer to, for example:
Workbooks.Close
(close ALL open workbooks)
Workbooks.Save
(save ALL the open workbooks)
Worksheets.PrintOut
(print ALL the worksheets in the workbook)
Worksheets.Add
(insert a new worksheet into the workbook)
Page 47
Referring by name
WorkBooks(Sales Analysis).Activate
(activate the open workbook named Sales Analysis)
WorkSheets(Sheet2).Activate
(activate the worksheet in the current workbook named Sheet2)
Page 48
The index number of a worksheet is as it appears from left to right. The worksheet at
the left of the workbook will always have an index number of 1, irrespective of its
name.
Eg:
Worksheets(2).Activate
or
Worksheets.Item(2).Activate
(activate the second worksheet from the left of the current workbook)
The object - Range - is also a collection (a collection of cells) although it is written in the
singular. To return a single range object, you refer to it by its absolute reference, eg:
Range(C10).Select
(select the cell C10)
You cannot refer to a cell by its index number using range. To refer to a cell by its
index number, use Cells, eg:
Cells(1).Select
or
Cells.Item(1).Select
or
Cells.Item(257).Select
Page 49
they are being used with. The Add method, for example, can be used in Excel 2007
with about 44 different objects!
It is not necessary to know all the different methods and properties associated with
each object in order to write useful and effective code. Listed below are some of the
more popular methods and properties used in conjunction with the objects given on
page 46.
Object
Methods(M) and
Properties (P)
Sample Code
Application
Quit (M)
Application.Quit
(exit Excel)
ScreenUpdating
(P)
Application.ScreenUpdating = False
DisplayAlerts (P)
Application.DisplayAlerts = False
Workbooks
Add (M)
Workbooks.Add
(adds a new workbook to the Excel application)
PrintOut (M)
Workbooks.PrintOut
(prints all open workbooks completely)
Workbooks(Sales Analysis).PrintOut
(prints the workbook named Sales Analysis)
Save (M)
Workbooks(Sales Analysis).Save
(saves (updates) the workbook named Sales Analysis)
Close (M)
Workbooks.Close
(closes all the open workbooks)
Workbooks(Sales Analysis).Close
(closes the workbook named Sales Analysis)
Worksheets
Add (M)
Worksheets.Add
(adds a new worksheet to the left of the current worksheet
in the current workbook)
Activate (M)
Worksheets(1).Activate
(makes the first sheet at the left of the workbook, the active
worksheet)
Delete (M)
Worksheets(London Data).Delete
(delete the sheet in the current workbook named London
Data)
Page 50
Object
Range
Methods(M) and
Properties (P)
Sample Code
Name (P)
PrintOut (M)
Worksheets(Summary).PrintOut
(print the sheet in the current workbook named
Summary)
Select (M)
Range(A1:C10).Select
(select the range A1 to C10)
Clear (M)
Range(B20).Clear
(clear cell B20 of both contents and formatting)
ClearContents
(M)
Range(B20).ClearContents
(clear cell B20 of just contents)
ClearFormatting
(M)
Range(B20).ClearFormatting
(clear cell B20 of just formatting)
Value (P)
Formula (P)
Range(A6).Formula = =sum(A2:A5)
(enter the formula SUM(A2:A5) in cell A6)
FormulaR1C1 (P)
Font (P)
Interior
Key Training Solutions Limited
Range(A1).Font.Color = vbBlue
(makes the font in cell A1 blue)
Page 51
Object
Methods(M) and
Properties (P)
PrintOut (M)
Sample Code
Range(A1:A8).Interior.Color = vbYellow
(makes the fill colour in cells A1 to A8 yellow)
Range(A1:D20).PrintOut
(prints just the range A1 to D20 on the current sheet)
Page 52
d) var4 = Range(A1:G30).Cells.Count
The value of var4 will be 210, the number of cells in the range A1 to G30.
Required/
Optional
Description
Before
Optional
An object that specifies the sheet before which the new sheet
is added.
After
Optional
An object that specifies the sheet after which the new sheet is
added.
Count
Optional
Type
Optional
All the additional arguments in this case are optional. If, however, you wanted to add
three new sheets before the first one at the left , the syntax would be as follows:
Page 53
Space
After argument
(2nd) (here left
blank)
Sheets.Add Sheets(1), , 3
Object
Method
Before
argument
(1st)
Count
argument
(3rd)
There must be a space before the word Add and the first argument.
The first argument describes the object before which you want to add the new
sheet (Sheets(1)).
The second argument is not required and left blank by typing commas with
nothing between them.
The final argument, if not used, should be omitted. Do not add any further
commas.
An alternative syntax that makes method arguments easier to use and understand uses
named arguments. In the above example, the syntax would be as follows:
Sheets.Add Before:=Sheets(Sheet1), Count:= 3
A space still needs to be added after the word Add, but the additional arguments that
you want to use are typed exactly as they appear in the Auto Quick Info Tip
immediately followed by a colon and an equal symbol (:=) and then their value. This
not only makes it clearer to read and understand, but by only entering the arguments
that you need, keeps the statement more concise.
Another example of a method with an optional argument is Copy (or Cut):
Range(A1:A10).Copy Destination:= Sheets(2).Range(B1)
That is certainly easier, quicker and more understandable than typing the following:
Range(A1:A10).Copy
Sheets(2).Activate
Range(B1).Select
Activesheet.Paste
An example of a method that needs a mandatory argument is Open when it refers to
the Workbooks object. Without the Filename argument, Excel would not know which
file you wanted to open!
Eg:
Workbooks.Open Filename:= s:\SharedData\Excel\Sales.xls
Key Training Solutions Limited
Page 54
A full list of arguments for the Open method (Excel 2003) is:
Page 55
Think of the Excel Object Model as the organisation chart of your own company or
organisation. At the top of the tree is the Managing Director, CEO or Chairperson, etc.
If you are very senior, you may work directly for that person (ie. you can be directly
controlled by that person) but in most cases, you will be further down the hierarchy
controlled by a manger at a lower level.
If someone asks you who you work for, you could say that you work for the MD, CEO,
or Chair (because ultimately, you do!), but you would normally quote your immediate
group or departmental manager.
Objects are, therefore, like levels of management, always refer to the one at the lowest
possible level. Think of it as always using the lowest common denominator.
Examples of common properties that can also be referred to as objects are:
Property(Object) Refers to
Examples
ActiveWorkbook
ActiveWorkbook.Save
The workbook
from which
the macro is
being run.
ActiveWorkBook.PrintOut
ActiveWorkbook.Close
variable = ActiveWorkbook.FullName
ActiveSheet
ActiveSheet.PrintOut
ActiveSheet.Delete
ActiveSheet.PageSetup.Orientation =
xlLandscape
variable = ActiveSheet.Item
ActiveCell
ActiveCell.HorizontalAlignment = xlCenter
ActiveCell.RowHeight = 20
ActiveCell.EntireColumn.Autofit
variable = ActiveCell.Address
SELECTION OR ACTIVECELL?
Discussion
The macro recorder is very fond of using Selection when ActiveCell would be more
appropriate, for example:
Range("D5").Select
Selection.Font.Bold = True
In the above case, using Selection has no detrimental effect but it is important to
understand the difference between ActiveCell and Selection.
Key Training Solutions Limited
Page 56
ActiveCell refers to one specific cell that has been selected or activated. Selection is
more appropriate when several cells have been selected. For example:
Range("D5").Select
ActiveCell.Font.Bold = True
but
Range("D5:E10").Select
Selection.Font.Bold = True
If the above piece of code had stated:
Range("D5:E10").Select
ActiveCell.Font.Bold = True
... only the cell D5 (the one in the top left of the
selected area) would be made bold.
Selection can refer to many groups (classes) of object, not just cells (range). In the code
below, all the charts on a sheet are selected and then deleted.
ActiveSheet.ChartObjects.Select
Selection.Delete
The following example counts the number of drawn objects (shapes) on the sheet, and
stores them in a variable named counter.
ActiveSheet.Shapes.SelectAll
counter = Selection.Count
The following example selects all the cells on the sheet and removes all the formatting,
leaving just the plain cell contents.
Cells.Select
Selection.ClearFormats
Page 57
Page 58
The VB Editor formats the words, Sub and End Sub with a blue font. This is to
highlight them as Key Words - main instructions of the VBA language - rather
than an object, method or property.
b) Statements
In between Sub and End Sub, come statements. Statements are the sentences
that make up the bulk of each sub procedure. Most (but not all) statements
carry out an action on an object by applying methods to it or by altering its
properties.
The number of statements (and other code) that can be written between Sub
and End Sub are too numerous to give here, but examples and principles given
earlier in this book should point you in the right direction for writing simple
but effective and useful sub procedures.
For example, the following add a new sheet to a workbook, moves it to the left
of the workbook and then enters and formats a title in cell A1:
Sub SetUpNewReport ()
Sheets.Add Before:= Sheets(1)
Range(A1).Value = Stock Report
Range(A1).Font.Bold = True
Range(A1).Font.Size = 20
Range(A1).Font.Name = Arial Black
Range(A1).Font.Color = vbBlue
End Sub
The following selects all the cells on the active sheet (the one that the macro is
being run from) and alters the column widths, row heights and font:
Sub FormatAllSheet()
Cells.Select
Selection.ColumnWidth = 20
Selection.RowHeight = 15
Selection.Font.Name = Calibri
Selection.Font.Size = 11
Range(A1).Select
End Sub
c) Capitalisation
VBA words always have the first character capitalised. Some VBA words are
made up of two or more words (eg. ActiveWorkbook; ActiveCell;
Page 59
e) Comments
It is always a good idea to add notes to a sub procedure, not only to describe
and/or remind yourself what is happening or why, but also for the benefit of
other people who may have to edit your code in the future.
Comments are added simply by preceding them with an apostrophe (). A
comment can be added on a line of its own, eg:
The following code formats the range with a currency style
Range(B16:F16).Style = Currency
Or, it can be added at the end of a statement, eg:
Range(B16).Formula = =SUM(B3:B15)
Page 60
The VB Editor formats comments in green to make them stand out more
clearly. Precede all comments with a blank line
f) Line Breaks
Some statements can be very long, especially where many arguments are being
used with a method, or your code is entering a long text string into a cell. This
results in part of the code extedning off the right edge of the screen and making
it difficult to read without scrolling.
Unlike normal word-processing where a line break can normally be created by
pressing Enter, it is not so straightforward in the VB Editor. Before you press
Enter to break a statement, you must type a line-continuation character an
underscore (_) preceded by a space.
The line-continuation character cannot be added just anywhere, it has to be
added where there is a natural gap in the statement, ie. not in between a single
word (eg. Range, xlDescending, False) or inside special characters (eg. :=)
Consider the following long statement that sorts a table of data (range A1:F12)
by column A in a descending order.
Range("A1:F12").Sort Key1:=Columns("A"), Order1:=xlDescending, Header:=xlGuess, MatchCase:=False
Line breaks could be added as follows:
Range("A1:F12").Sort Key1:=Columns("A"), Order1:=xlDescending, _
Header:=xlGuess, MatchCase:=False
or:
Range("A1:F12").Sort Key1:=Columns("A"), _
Order1:=xlDescending, Header:=xlGuess, _
MatchCase:=False
But NOT:
Range("A1:F12").Sort Key1:=Colu _
mns("A"), Order1:=xlDescending, Header:=xl _
Guess, MatchCase:=False
In fact, if you attempted to write the above example, you would receive the
following message.
Page 61
In the case of long text strings, line breaks need to have added an ampersand
concatenation character (&) placed at the beginning of the continuation line as
follows: .
Range(B2).Value = Fourscore and seven years ago our fathers " _
& "brought forth, on this continent, a new nation, " _
& "conceived in liberty, and dedicated to the " _
& "proposition that all men are created equal."
Page 62
Note how by using a With ... End With block, repetitive typing of Range(A1) is
avoided: .
Sub SetUpNewReport ()
With Range(A1)
.Value = Stock Report
.Font.Bold = True
.Font.Size = 20
.Font.Name = Arial Black
.Font.Color = vbBlue
End With
End Sub
By using a nested With ... End With block inside the first one, repetitive typing of
.Font can also be avoided:
Sub SetUpNewReport ()
With Range(A1)
.Value = Stock Report
With .Font
.Bold = True
.Size = 20
.Name = Arial Black
.Color = vbBlue
End With
End With
End Sub
Referring to ranges by using the Cells method (eg. Cells(1) , Cells (2 , 2) , etc.)
The first two methods have already been described in previous lessons (see page 49).
Key Training Solutions Limited
Page 63
The best way of describing using the Offset property is to think of it as a way of
referring to a cell that is away from another cell by a certain number of rows and
columns.
Although Offset is a property and properties are normally equal to something, Offset
takes an argument in brackets as follows:
Offset(rowoffset , columnoffset)
RowOffset is the number of rows away from the object that you want to refer. Positive
values are offset downward, and negative values are offset upward.
ColumnOffset is the number of columns away from the object that you want to refer.
Positive values are offset to the right, and negative values are offset to the left.
Offset(-1 , 0)
Up one row, same
column
Offset(0 , -1)
Same row, left one
column
Offset(0 , 1)
Same row, right one
column
Offset(1 , 0)
Down one row, same
column
The following example puts a value of 100 to the cell that is one row below cell C2 and
two cells to the right of C2 (ie. cell E3): .
Range("C2").Offset(1 , 2).Value = 100
An advantage of the Offset function in VBA is that you can do things to a cell away
from the one that is currently active without having to select it. Not only does this
create more concise code, but it can significantly speed up its execution. The following
code enters random numbers between 1 and 50 into the active cell and all the cells
surrounding it without actually selecting them.
Page 64
Sub EnterRandomNumbers
With ActiveCell
.Value = Rnd * 50
.Offset(-1 , 0).Value = Rnd * 50
.Offset(0 , 1).Value = Rnd * 50
.Offset(1 , 0).Value = Rnd * 50
.Offset(0 , -1).Value = Rnd * 50
End With
End Sub
Some errors, however, cannot be identified until you actually run the sub procedure.
These usually (but not always) show up as Run-time errors and are characterised by
the following message window:
Page 65
can, under certain circumstances, help you identify the problem and is an essential tool
is writing error trapping code into your sub procedure. This, however, is outside the
scope of this particular course.
In some cases, the Run-time error occurs at the very start of the sub procedure and no
statements are executed. In other cases where the Run-time error has occurred in the
middle or near the end of the sub procedure, some actions will have been carried out
before it came to a stop without completing through got the end.
You have several options on how to deal with a Run-time error message:
a) Click Help to read about the problem
b) Click End to terminate the sub procedure
c) Click Debug to take you to the VB Editor and to the statement where the error
occurred. The statement will be highlighted in yellow (called Step Mode).
If you understand what the error is and can fix it, you should then click the Continue
button on the toolbar of the VB Editor in order for the sub procedure to attempt the
statement again and, hopefully, complete through to the end.
If you are unable to deal with the error, you should click the Reset button on the
toolbar of the VB Editor in order to exit the sub procedure. You should then consult the
person who wrote the macro and seek their advice and co-operation is resolving the
problem.
In the case of a run-time error, you must click either the Continue of the Reset button.
If you do not you will be unable to run any other macros.
Page 66
Procedures
1. Click the Debug button
window.
Procedures
1. Launch the VB Editor.
Page 67
108.
on the toolbar.
109.
Click the drop down list in the top left corner of the Object
Browser.
110.
Select Excel.
111.
112.
Right-click an object and select Help from the menu to
learn more about it.
113.
114.
View its associated methods
the right-hand pane.
and properties
in
115.
Right-click a method or property and select Help to learn
more about it.
116.
Double click a module or Excel object in the Project
Explorer pane to close the Object Browser.
Page 68
EXERCISE
WRITING SUB PROCEDURES
1. Launch the VB Editor.
2. Insert a module into the Personal Macro Workbook (personal.xls).
3. Create a new sub procedure named, OpenAndFormat.
4. Enter into the sub procedure a comment stating: This macro opens
the Regional Sales workbook and formats the headings on the first
sheet.
5. Type the first statement for the sub procedure into the module
sheet. The statement must open the workbook named Regional
Sales.xls from the train folder on the c:\ drive.
6. The next statement must activate the first sheet at the left of the
workbook.
Page 69
8. The next group of statements must format the active cell with:
A font size of 18
9. The next statement must change the column width of the active
cell to 20.
11. The next statement must insert an entire row where the active cell
is.
13. The next statement must format the selected range with:
A bold font
14. The final statement of the sub procedure must select cell A1
Page 70
17. Save the Regional Sales workbook then exit Excel and save the
Personal Macro Workbook, if prompted.
Page 71
Operator
Equal to
>
Greater than
>=
<
Less than
<=
<>
Not equal to
Page 73
If to close off the control structure. Any code following the End If is NOT
dependant on the test being true.
If <test> Then
<actions if true>
End If
For example:
If Range(A3).Value > 100 Then
Range(A3).Font.Bold = True
Range(A3).Font.Size = 14
Range(A3).Font.Color = vbBlue
Indentations to the
actions if true code is
added purely for
clarity and to give
structure to the block.
End If
Although, you can use the single-line form for short, simple tests. However, the block
form provides more structure and flexibility than the single-line form. Using block
form makes it easier to read, maintain, and test.
Other examples of tests that might be used as tests in an If-Then control structure are:
If ActiveCell.Value = Bonus Then <action if true>
(If the active cell equals the word bonus, then...)
If Range(C10).Value >= 100 Then <action if true>
(If cell C10 contains a value greater than or equal to 100, then...)
If ActiveCell <> Then <action if true>
(If the active cell is not empty (contains no text), then...)
If ActiveCell.Offset(0, 1).Value > 100 Then <action if true>
(If the cell on the same row and one column to the right of the active cell is
greater than 100, then...)
If Range(A6).Font.Bold = TRUE Then <action if true>
(If cell A6 contains bold font, then...
Page 74
A test can be elaborated further by adding And and/or Or conditions to it. The syntax
is as follows:
If <test1> And <test2> And <test3> Then
<actions if true>
End If
In the above example, test1, test2 and test3 must ALL be true for the actions if true to
occur. If even one of the tests is false, the If ends without carrying out any actions.
In the following example only ONE of the test needs to be true in order for the actions if
true to occur.
If <test1> Or <test2> Or <test3> Then
<actions if true>
End If
And and Or can also be mixed together, for example:
If <test1> And <test2> Or <test3> Then
<actions if true>
End If
Procedures
1. Position the cursor in the macro where you want to place the
statement.
2. Type If.
3. Type a space.
4. Type a valid test.
5. Type a space.
6. Type Then.
7. Press Enter.
8. Type the statements that you want the macro to perform if the
test is true.
9. Press Enter.
10. Type End If.
11. Add additional code as necessary.
Page 75
Procedures
1. Position the cursor in the sub procedure where you want to
place the statement.
2. Type If.
3. Type a space.
4. Type a valid test.
5. Type a space.
6. Type Then.
7. Press Enter.
8. Type the statements that you want the sub procedure to
perform if the test is true.
Page 76
9. Press Enter.
10. Type Else.
11. Type the statements that you want the sub procedure to
perform if the test is false.
12. Press Enter.
13. Type End If.
14. Add additional code as necessary.
Page 77
Else always comes last in the block to cover any possibilities that have not been
eliminated by previous tests.
All test whether the initial If or subsequent ElseIfs must be followed by Then.
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type If.
3. Type a space.
4. Type a valid test.
5. Type a space.
6. Type Then.
7. Press Enter.
8. Type the statements that you want the sub procedure to
perform if the test is true.
9. Press Enter.
10. Type ElseIf.
11. Type a space.
12. Type a valid test.
13. Type a space.
14. Type Then.
15. Press Enter.
Key Training Solutions Limited
Page 78
16. Type the statements that you want the sub procedure to
perform if the test is true.
17. Press Enter.
18. Type Else.
19. Type the statements that you want the sub procedure to
perform if the test is false.
20. Press Enter.
21. Type End If.
22. Add additional code as necessary.
Page 79
If, however, the active cell does not contain Status A, control passes to the second
Case Is and if the active cell contains the value Status B, the font in the active cell is
made green.
If the active cell does not contain Status B either, then control passes to the Case Else
and under all other circumstances makes the font red.
Select Case ActiveCell.Value
Case Is = Status A
Activecell.Font.Color = vbBlue
Case Is = Status B
Activecell.Font.Color = vbGreen
Case Else
Activecell.Font.Color = vbRed
End Select
The usual comparison operators can be used after the Case Is, such as:
Case Is > <value>
Case Is >= <value>
Case Is < <value>
Case Is <= <value>
Case Is <> <value>
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type Select Case.
3. Type a space.
4. Type the object.property that you want to carry out tests on.
Eg. ActiveCell.Value
5. Press Enter.
6. Type Case Is.
7. Type a valid comparison operator, eg. = or > or < or >= or <=
or <>.
8. Type the value that you want to compare the object/property
against.
9. Press Enter.
Page 80
10. Type the statements that you want the sub procedure to
perform if the test is true.
11. Press Enter.
12. Add further Case Is <comparison operator> <value>
statements, if necessary.
13. At the end of the Case Is statements, type Case Else if there is
a final set of actions that you want the sub procedure to
perform if none of the previous tests are true.
14. Press Enter.
15. Type End Select.
16. Add additional code as necessary.
Page 81
example below, cells in a column (starting at the top of the column) are formatted bold
until an empty one is reached.
Do Until ActiveCell.Value =
(Do the following statements until the active cell is empty)
ActiveCell.Font.Bold = True
(Make bold the font of the active cell)
ActiveCell.Offset(1,0).Select
(From the active cell, move down 1 row, same column)
Loop
(Return to Do Until and check if the active cell is empty. If TRUE, repeat the statement; if
FALSE continue the sub procedure from after Loop.)
In the same example, a Do While loop would look like this:
Do While ActiveCell.Value <>
(Do the following statements while the active cell is not empty)
ActiveCell.Font.Bold = True
(Make bold the font of the active cell)
ActiveCell.Offset(1,0).Select
(From the active cell, move down 1 row, same column)
Loop
(Return to Do While and check if the active cell is not empty. If TRUE, repeat the statement; if
FALSE continue the sub procedure from after Loop.)
It is important to check the condition before entering a loop. If the condition is FALSE
the contents of the loop will never execute. In cases where this is an issue, use the
following to ensure that the statements are executed at least once:
Do
(Do the following statements)
ActiveCell.Font.Bold = True
(Make bold the font of the active cell)
ActiveCell.Offset(1,0).Select
(From the active cell, move down 1 row, same column)
Loop Until ActiveCell =
(Check if the active cell is empty. If TRUE, return to Do and repeat the statements; if FALSE
continue the sub procedure from after Loop Until...)
Key Training Solutions Limited
Page 82
Or...
Do
(Do the following statements)
ActiveCell.Font.Bold = True
(Make bold the font of the active cell)
ActiveCell.Offset(1,0).Select
(From the active cell, move down 1 row, same column)
Loop While ActiveCell <>
(Check if the active cell is not empty. If TRUE, return to Do and repeat the statement; if FALSE
continue the sub procedure below Loop While...)
The Not operator can be used in a Do loop to reverse the logic of the condition. The
syntax would be, for example:
Do Until Not ActiveCell.Value =
Statement(s)
Loop
This would be the same as:
Do Until ActiveCell <>
Statement(s)
Loop
Page 83
2. Move across a row of data until the cell is found containing todays date:
Do Until ActiveCell.Value = Date
ActiveCell.Offset(0,1).Select
Loop
3. Move down a column of data until you get to a cell containing bold font. Add a
blue font colour to cells with a value higher than 100.
Do Until ActiveCell.Font.Bold = TRUE
If ActiveCell.Value > 100 then
ActiveCell.Font.Color = vbBlue
End If
ActiveCell.Offset(1,0).Select
Loop
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type Do Until or Do While.
3. Type a space.
4. Type the condition for the Until or While,
5.
6. Press Enter.
7. Type the statements that you want the sub procedure to
perform until or while the condition is true.
8. Press Enter.
9. Type Loop.
10. Add additional code as necessary.
Page 84
EXERCISE
DECISIONS-MAKING CODE AND DO LOOPS
1. Open the file Practice Decision.
2. Insert a module sheet to the workbook and write a sub
procedure named, CheckStock which uses an IF statement
block to check the value of an active cell and if the value is
less than 300 enters Order now into the cell to the right.
3. Place a DO loop around the IF statement so that it runs
down a column until it comes to an empty cell.
4. On the Inventory sheet, select cell C5 and run the
CheckStock sub procedure.
5. Edit the sub procedure so that in cases where the value is
not less than 300, the text, "Hold Order" is entered into the
cell to the right.
6. Delete the text in cells D5:D10 and run the CheckStock
procedure again to test your code.
7. Finally, edit your procedure again so that if the cell being
tested is equal to 0, the words, "Out of stock" is entered into
the cell to the right and formatted to RED font.
8. Run to test the procedure again.
9. Save and close the file.
10. Open the file Personnel Record.
11. Write a procedure named BonusAward and use a CASE
SELECT statement block and a DO statement block to carry
out the following actions on the table:
Test
2%
3%
5%
Page 85
LESSON 6
DATA VARIABLES
In this lesson, you will learn how to:
Create data variables and learn how to assign values to them
Declare variables
DATA VARIABLES
Discussion
Data variables are used to hold information temporarily whilst a sub procedure is
running; information that can be used later in the sub procedure to carry out a
calculation or make a decision. In some cases, the information stored in the variable
can be returned to an Excel workbook to achieve a result or carry out an action.
One way of thinking of a variable is to look at it as being a container into which you
can put something. This something can be many things, eg:
A text string
A number
A date
Variables can also help make your sub procedures more interactive. Consider the
following statement that opens an Excel file:
WorkBooks.Open (Sales Data.xls)
(Open the Excel file named Sales Data)
Now consider the following where cell A1 contains the text, Sales Data.xls:
fileTo Use = Range(A1).Value
(This creates a variable named fileToUse and stores in it the text, Sales Data)
WorkBooks.Open (fileToUse)
(This uses the text stored in the variable, fileToOpen, to open the workbook)
The second example provides more flexibility because it is easier to change the
contents in cells A1 with the name of the file that you want to open, than accessing the
module and changing the code in the sub procedure.
Page 87
cause ambiguity and it is better to use descriptive, but concise, names for your
variables, eg: newname, salesfig, startdate, numcells.
A variable name must start with a letter and not a number. Numbers can be
included within the name, but not as the first character, eg. salesfig1 but not
1salesfig.
The first character of a variable name should be left lowercase. Because VBA
words always start with an uppercase character (eg. ActiveCell, WorkBook,
Cells), keeping the first character lowercase helps make your variables stand
out more clearly in the sub procedure.
Avoid using names that conflict with VBA words such as: activecell,
sheets, font, cells, etc.
Spaces cannot be used in variable names. You can separate words by either
capitalisation, eg. newName, or by using the underscore character, eg.
new_name.
myNum = Cells(3,4).Value
2.
Giving the variable a value, either within the sub procedure or via user interaction
(eg. by means of an input box, see page 112).
firstNum = 10
secNum = 20
thirdNum = firstNum * secNum
MsgBox thirdNum.
Page 88
WorkBooks.Open (fileToUse)
3.
numCells = Selection.Cells.Count
celAddr = Cells(3,4).Address
Variables can change their values during the execution of a sub procedure. The
following example uses the value of the variable tempVal in a calculation, and then
changes it to a different value for a second calculation.
tempVal = 0.15
calc1 = ActiveCell.Value * tempVal
tempVal = 0.22
calc2 = ActiveCell.Value * tempVal
Another example of changing the value of a variable is for counting the number of
times that a condition is encountered, or where there is a need to count the number of
times that a loop has executed.
The following example uses a variable, numBold to count the number of cells in a
column containing bold font. It then returns the value of counter into cell A1.
Page 89
counter = 0
(Create a variable named counter and store in it a zero)
Do Until ActiveCell.Value =
(Do the following statements until the active cell is empty)
If ActiveCell.Font.Bold = True Then
(If the active cell contains bold font then...)
counter = counter + 1
(Increase the value of counter by 1 (ie. make the new value of counter
its old value + 1))
End if
ActiveCell.Offset(1,0).Select
(From the active cell, move down 1 row, same column)
Loop
(Return to Do Until and check if the active cell is empty. If FALSE, repeat the
statement; if TRUE continue the sub procedure from after Loop.)
Range(A1).Value = counter
(Return to cell A1 the value of counter)
Procedures
1. Position the cursor in the sub procedure code where you want
to create the variable.
2. Type a name for the data variable keeping in mind the naming
rules.
3. Type =.
4. Type a value for the variable; this can be a number, a string, a
boolean expression (True or False) or an object/property that
returns one of the above values,
5. eg. ActiveWorkBook.Name or ActiveCell.Value
6. Press Enter.
7. Add additional code as necessary.
The following example, uses two counters. One to count the number of cells
containing bold font (counter1) and the second to count the number of times that the
loop has executed (counter2). Counter2, therefore, counts the number of cells that
have been checked in the column.
Page 90
counter1 = 0
counter2 = 0
(Create variables named counter1 and counter2 and store in them zero)
Do Until ActiveCell.Value =
(Do the following statements until the active cell is empty)
If ActiveCell.Font.Bold = True Then
(If the active cell contains bold font then...)
Counter1 = counter1 + 1
(Increase the value of counter1 by 1 (ie. make the new value of
counter its old value + 1))
End if
ActiveCell.Offset(1,0).Select
(From the active cell, move down 1 row, same column)
counter2 = counter2 + 1
(Increase the value of counter2 by 1. Because this statement will occur each time the
loop is repeated irrespective of whether the IF is true or false, it will count the total
number if times that the loop has executed)
Loop
(Return to Do Until and check if the active cell is empty. If FALSE, repeat the
statement; if TRUE continue the sub procedure from after Loop.)
Range(A1).Value = counter1
Range(A2).Value = counter2
(Return to cell A1 the value of counter1 the number of cells containing bold font
and return to cell A2 the value of counter2 the number of cells checked)
VARIABLE TYPES
Discussion
It was mentioned previously that variables can store many things (see page 87). It is,
therefore, good practice (although not always necessary in VBA) to tell the sub
procedure in advance, what variables are going to be used and the type of data that is
going to be stored in them.
By doing this, you are not only helping to prevent potential errors and ambiguity in
the sub procedure, but also improving the efficiency and performance of the sub
procedure by assigning an appropriate amount of computer memory for storing the
variable. Although this will have relatively little impact on a small sub procedure that
uses just a few variable, it could slow down or crash the computer in cases where there
are hundreds of lines of code using dozens of variables.
The process of doing this is called declaring a variable, .and is usually carried out at
the beginning of a sub procedure by using a Dim statement as follows: .
Key Training Solutions Limited
Page 91
The following provides a list of the more commonly used variables types for storing
data.
Data type
Memory size
Storage capability
Byte
1 byte
0 to 255
Boolean
2 bytes
True or False
Integer
2 bytes
-32,768 to 32,767
Long
4 bytes
-2,147,483,648 to 2,147,483,647
Single
4 bytes
Double
8 bytes
-1.79769313486231E308 to
-4.94065645841247E-324 for negative values;
4.94065645841247E-324 to 1.79769313486232E308 for
positive values
Currency
8 bytes
-922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal
14 bytes
+/-79,228,162,514,264,337,593,543,950,335 with no
decimal point;
+/-7.9228162514264337593543950335 with 28 places
to the right of the decimal; smallest non-zero
number is
+/-0.0000000000000000000000000001
Date
8 bytes
String
10 bytes +
(variable-length) string length
Key Training Solutions Limited
0 to approximately 2 billion
Page 92
During a sub procedure, a variable may be assigned different values and data types.
The last declaration will determine what the variable is allowed to store.
In the following example, the variable myVar is used firstly to store a number, and
then to store a date.
Dim myVar as Single
myVar = 1234.5678
Dim myVar as Date
myVar = #01/05/2009#
If a specific data type is assigned to a variable, the variable will only be able to hold
that type of data. If storing a different data type is attempted, an error message will be
displayed when the sub procedure is run.
Procedures
1. Position the cursor on the line below the sub procedure name.
2. Type Dim.
3. Type a space.
4. Type a name for the first variable that you intend using in the
sub procedure.
5. Type a space.
6. Type As.
7. Type a space.
8. Type (or select from the members list) the type of data that the
variable will store.
9. Press Enter.
10. Add additional code as necessary.
Page 93
EXERCISE
TO ASSIGN VALUES TO VARIABLES.
1. Open the file, Practice Variables.
2. Create a sub procedure named, VatCalc that:
returns in the cell to the right of the active cell the amount
plus VAT
Page 94
ActiveCell.Offset(1,0).Select
Next counter
The following examples uses a variable (numCells) to count the number of cells in a
selected range (a column). It then starts with the first cell in the range (ActiveCell) and
loops through the statements as many times as there are cells in the range, doubling
their value.
Page 96
Using Step
This final example uses step to create an interval of 2 in the counting. The first time
round the loop, the value of the variable (i) will be 1; the second time the value of the
variable will be 3 (1 + 2); the third time 5 (3 + 2), etc.... The result of this is that the
column will be filled with 50 odd numbers in alternate cells.
Key Training Solutions Limited
Page 97
Dim i as Byte
For i = 1 To 100
Cells(i , 1).Value = i
Next i
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type For.
3. Type a space.
4. Create a variable by entering a name for it, eg. counter
5. Type =.
6. Type a number from where you want the loop to start.
7. Type To.
8. Type a number from where you want the loop to end.
9. If the loop must count between start and end with an interval
that is not equal to 1 (the default), type a space.
10. Type Step.
11. Type a space.
12. Type a number for the interval that you want the loop to
count.
13. Press Enter.
14. Type the statements that you want the sub procedure to repeat
as defined by the For ... To statement.
15. Press Enter.
16. Type Next.
17. Type a space.
18. Type the variable name used in the For... To statement at the
beginning of the loop
19. Press Enter.
20. Add additional code as necessary.
Page 98
Page 99
Well, think of collection (or array) as a container with lots of sections in it, rather like a
pigeon hole unit in a post room. Each element is one of the holes in the unit. The For
Each ... Next loop repeats the statements for as many pigeon holes as there are in the
unit!
So, how do we define the pigeon hole unit in Excel? In many cases it will be a range of
cells or another collection of objects. The analogy, therefore, works well because if we
take a range of cells, they do, indeed, resemble a pigeon hole unit with each cell
representing one of the holes.
The following example uses a For Next...Each loop to enter a zero into any blank cells
in the range B2 to D200.
Page 100
It is much easier and more convenient to use to carry out looping actions
when there is a mixture of columns and rows. Try using a Do loop or a For
Next loop in the above example!
It can be used to loop through other types of object collections in a way that
other loops can not.
Other Collections
We have examined above the use of a range as the collection (or array). Examples of
some other collections that can be used is given below.
Object
Collection
Syntax example
Workbooks (Excel
files)
WorkBooks
Page 101
WorkSheets
Sheets
Charts (Graphs)
ChartObjects
Add Ins
AddIns
Toolbars (Excel
2000 2003 only)
CommandBars
Page 102
In the following example, the user has already selected several charts on a worksheet
(by clicking the first one and then holding down the SHIFT key and clicking all the
others). The loop then changes their background colour to cyan and prints them all.
Dim chrt As Object
For Each chrt in Selection
Chrt.Chart.ChartArea.Interior.Color = vbCyan
Chrt.Chart.PrintOut
Next chrt
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type For Each.
3. Type a space.
4. Type a variable name to represent each of the elements that
you want the loop to act on.
5. Type a space.
6. Type In.
7. Type the name of a valid object or reference to an object,
8. eg. Range(A1:C10) or Selection or Sheets
9. Press Enter.
10. Type the statements that you want the sub procedure to repeat
as defined by the For ... Each statement.
11. Press Enter.
12. Type Next.
13. Type a space.
14. Type the variable name used in the For... Each statement at the
beginning of the loop
15. Press Enter.
16. Add additional code as necessary.
Page 103
Page 104
EXERCISE
CREATE A FOR LOOP STRUCTURE.
1. Open the file Practice Loops. Enable the macros, if prompted.
2. Test the CheckDept procedure. The macro runs just once,
identifies that Davis works in the Sales department and
emboldens the font in cell B5.
3. Edit the procedure as necessary so that it runs 12 times in
order to check all the departments in column C.
4. Test the macro and correct any errors.
5. Save and close the file.
6. Open the file Student Grades.
7. Edit the CollegeIdentify procedure with a FOR EACH NEXT
loop so that the macro runs on all the cells in range C2:C18.
8. Test the macro and correct any errors.
9. Save and close the file.
Page 105
Page 106
Buttons, (optional), describes the number and type of buttons displayed in the
dialog box; determines the icon style; determines which button is the default;
and determines the modality (on/off position) of the message box.
Helpfile and Context, (optional), identify which Help file to use to provide
context-sensitive Help for the message box. (It is very unusual to use this
because the helpfile needs to be constructed and compiled using Microsoft tools
not provided with Office.
To use the message box function purely to display a message, it is only necessary to use
the prompt argument, eg. :
MsgBox The procedure has successfully completed
Embellishments can be added to the message box by adding an icon and a window
title, eg.
MsgBox The procedure has successfully completed, vbInformation, Duplicate Checker
Page 107
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type MsgBox.
3. Type a space.
4. Type the text string, variable name or combination of both
(separated by - space ampersand space ( & )) that you wish the
message box to display.
5. Press Enter.
6. Add additional code as necessary.
Example A
Example B
To make the message box interactive, the arguments must be put inside brackets. The
following code will display Example A above.
MsgBox ("Do you want to continue deleting the data", vbYesNo, "Delete Confirm")
Prompt
Buttons
Title
Page 108
The buttons argument consists of constants or values from each of the following three
groups:
Value
Display
vbOKOnly
OK button only
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
Icon style:
Constant
Value
Display
vbCritical
16
vbQuestion
32
vbExclamation
48
vbInformation
64
Icon
Default Button:
Constant
Value
Default
vbDefaultButton1
vbDefaultButton2
256
vbDefaultButton3
512
The buttons argument of the message box function can hold three pieces of
information separated by a plus (+) symbol. Using the following code as the buttons
argument will produce Example C below.
vbYesNo + vbQuestion + vbDefaultButton2
Page 109
vbQuestion
vbYesNo
vbDefaultButton2
(second from left)
A more concise method of writing the above sample of code would be to use the
numeric values for the arguments, eg.
4 + 32 + 256
Im sure that the average user will, however, find it easier to remember the vb
constants, viz. vbYesNo + vbQuestion + DefaultButton2.
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type a variable name to store the value of whichever button is
clicked in the message box, eg. response.
3. Type =.
4. Type MsgBox.
5. Type an opening bracket ( .
6. Type a speech mark (Shift 2).
7. Type a prompt for the message box, ie. the message that you
want it to display, eg. Do you want to continue?
8. Type a speech mark (Shift 2).
9. Type a comma.
10. Type the necessary value to indicate which buttons you want
the message box to display, eg. vbYesNo.
11. If you wish to add an icon
and/or default button to the
message box, type a plus
symbol (+).
Page 110
Value
Button Selected
vbOK
OK
vbCancel
Cancel
vbAbort
Abort
vbRetry
Retry
vbIgnore
Ignore
vbYes
Yes
vbNo
No
In the following example, the message box offers a yes/no response. If the user clicks
yes, then the procedure will delete all the data from the sheet. If the user clicks no, the
procedure will terminate.
If MsgBox (Do you want to delete all data, vbYesNo + vbCritical) = vbYes Then
ActiveSheet.Cells.Clear
End If
The result of the message box (ie. whether the yes or no button is clicked) can be stored
in a variable and the code could also be written:
Key Training Solutions Limited
Page 111
or
If response = 6 Then
ActiveSheet.Cells.Clear
End If
Procedures
1. (The procedure below assumes a message box containing Yes
and No buttons. It can be adapted, however, to respond to any
set of buttons (eg. vbOKCancel, vbRetryCancel etc.))
2. Position the cursor in the sub procedure code where you want
to place the statement.
3. Create an interactive message box as described in the previous
topic of this lesson.
4. Press Enter.
5. Type If.
6. Type a space.
7. Type the variable name that you have used to store the
response from the message box.
8. Type a space.
9. Type = vbYes.
10. Type a space.
11. Type Then.
12. Type the statements that you want the sub procedure to
perform if the user has clicked the Yes button.
13. Press Enter.
14. Type Else.
15. Press Enter.
16. Type the statements that you want the sub procedure to
perform if the user has clicked the No button.
17. Press Enter.
18. Type End If.
19. Press Enter.
20. Add additional code as necessary.
Page 112
Prompt, the only required argument. A text string, surrounded by quotes, that
you would like to display in the dialog box. The maximum length is 1024
characters.
Title, (optional), represents what is displayed on the title bar of the dialog box.
The default title will be Microsoft Excel.
xpos, and ypos, (optional), are numeric expressions that specify the horizontal
and vertical distances from the top left corner of the screen where the top left
corner of the input box will be located.
If xpos and ypos are omitted, the dialog box is centred horizontally on the
screen, about one-third of the way down from the top. (It is very unusual to
use this argument, because the exact position varies between types of monitor,
even though Excel tries to compensate for this). The measurement unit used is
twips, and there are approximately 10 twips to a pixel!
Helpfile, and context, (optional), identify which Help file to use to provide
context-sensitive Help for the dialog box. (It is very unusual to use this,
because the helpfile needs to be constructed and compiled using Microsoft tools
not provided with Office).
The following example displays the following dialog box. The users response is stored
in a variable called yName.
Dim yName as String
yName = InputBox("Please Enter Your Name")
Page 113
If the user clicks OK or presses Enter, the InputBox function returns to the variable
yName whatever was typed in the text box. If the user clicks Cancel or presses Esc, the
InputBox function returns a zero length (empty) string.
The following example adds a title at the top of the input box window and adds a
default text string in the text box.
Dim yName as String
yName = InputBox("Type your company name", "Company Name Input", "Key Training")
The input box may be invoked wherever there is a need to prompt the user for
information to use in a sub procedure. The sample code below gives two examples of
how it might be used.
Sample A Prompt the user for a name to give the current sheet
Dim shtName as String
shtName = InputBox(What name do you wish to give the current worksheet?)
ActiveSheet.Name = shtName
Or...
Dim shtName as String
ActiveSheet.Name = InputBox(What name do you wish to give the current worksheet?)
Page 114
Sample B Prompts user for two inputs, carries out a calculation and returns the result
in a message box and in cell A1.
Dim amount as Single
Dim rate as Single
amount = InputBox (Enter your sales figure)
rate = InputBox(Enter your commission rate as a decimal percentage, eg. 0.15)
commission = amount * rate
MsgBox Your commission for this sale is & commission
Range(A1).Value = commission
Or...
MsgBox Your commission for this sale is & Format(commission,#,##0.00)
Range(A1).Value = Format(commission,#,##0.00)
Procedures
1. Position the cursor in the sub procedure code where you want
to place the statement.
2. Type a variable name in which the data entered in the input
box will be stored.
3. Type =.
4. Type InputBox.
5. Type an opening bracket ( .
6. Type a speech mark (Shift 2).
7. Type the text that you want the input box to display.
8. Type a speech mark (Shift 2).
9. Type a comma.
10. If you wish to add a title to the
input box, type a comma
Page 115
Page 116
EXERCISE
USING INTERACTIVITY
1. Open the file MsgBoxButtons. Enable the macros, if prompted.
2. Click the Add Forecast macro button on the Buttons sheet. This
copies and pastes data from the Forecasts sheet.
3. Click the Clear Sheet macro button. This deletes out all data from
the Buttons sheet.
4. Edit the Add_Forecast and Clear_Forecast procedures so that a
message box appears, asking the user if:
a) they are sure they want to continue;
b) giving them Yes and No buttons to choose from;
c) giving a message box title of "Confirm."
5. Run both macros to check that they work.
6. Run the Add_Forecast procedure.
7. Create a new procedure called InputData that:
prompts the user with two Input Boxes for values to enter
for the projected incomes of the two countries (Great
Britain and United States).
have as its title, the name of the country to which it
applies.
enters the values in the appropriate cells (E7 and E8).
8. Assign the procedure to a worksheet button.
9. Run the macro to check that the procedure works, entering some
made up information of your own into each input box.
10. Save and close the file.
Page 117
Page 118
Appendix I - Security
SECURITY LEVELS
Discussion
While many macros are simply recordings of your keystrokes and mouse actions, VBA
developers can write macros that carry out many commands on your computer. As a
result, hackers can introduce harmful code onto your computer by writing macros that
release a virus when run.
When opening an Excel file containing macros, therefore, Excel uses various criteria to
ensure any macros contained therein are safe. The level and thoroughness at which
Excel does this is determined by the security settings in force on your computer. The
criteria for this varies depending on whether the workbook is being opened from a
trusted location and/or if it is digitally signed.
High
Medium
Page 119
Appendix I - Security
With signed macros, the source of the macro and the status of the
signature determine how signed macros are handled.
Low
In Excel 2007, macro security has changed significantly. Although the security levels
are comparable with earlier versions of Excel, the way in which Excel 2007 warns you
about potential risks has changed. Instead of a message box appearing on the screen, a
Message Bar appears above the work area at the left and below the Ribbon. These are
referred to as notifications.
Page 120
Appendix I - Security
Page 121
Appendix I - Security
Procedures
1. Click the Microsoft Office button.
2. Click Excel Options.
3. Select Trust Center in the pane at the left.
4. Click the Trust Center Settings... button.
5. Select Trusted Locations in the pane at the left, if necessary.
6. Note the existing default trusted locations and assess whether it is
practical to use them.
7. If the answer to 6 above is yes, then click Cancel and leave the
settings unchanged.
8. If the answer to 6 above is no, then
Key Training Solutions Limited
Page 122
Appendix I - Security
Click Tools
Click OK
Page 123
Index
INDEX
Coding
ActiveCell ................................................. 57
capitalisation ............................................. 60
comments .................................................. 60
concatenation character ............................ 62
indentations............................................... 60
line breaks ................................................. 61
Run-time error .................................... 65, 66
Selection ................................................... 56
statements, definition ................................ 59
sub procedures, definition......................... 58
the OFFSET function................................ 64
white space ............................................... 60
With... End With block ....................... 62, 63
Control Structures
Do Loop .............................................. 81, 82
ElseIf................................................... 77, 78
For Each examples.......................... 101, 102
For Each loop ........................... 99, 100, 103
For Next examples .............................. 96, 97
For Next loop ...................................... 96, 98
If...Then .................................. 73, 76, 78, 80
If...Then...Else .......................................... 76
nested For Each examples ...................... 103
nested For Each loops ............................. 103
nested For Next examples......................... 99
nested For Next loops ............................... 99
Select Case.......................................... 79, 80
using Step with For Next .......................... 97
Input Box
definition................................................. 113
examples ................................................. 113
Keywords
End Sub .................................................... 58
Sub ............................................................ 58
Macro buttons
copying ..................................................... 39
creating ..................................................... 37
creating in Excel 2000 - 03 ....................... 37
creating in Excel 2007 .............................. 38
deleting ..................................................... 42
moving ................................................ 40, 41
sizing................................................... 40, 41
using ......................................................... 37
Macros
assigning a shortcut key ............................ 30
assigning to a menu .................................. 34
assigning to a toolbar button ..................... 31
defining ....................................................... 6
deleting custom button.............................. 36
deleting from a menu ................................ 36
Key Training Solutions Limited
description .................................................. 8
naming ........................................................ 7
opening ............................................... 13, 16
personal macro workbook .......................... 7
recording .................................................... 6
running ..................................................... 10
saving ................................................. 12, 13
security warnings Excel 2000 - 03 ........... 14
security warnings Excel 2007 .................. 14
shortcut key ................................................ 7
storing......................................................... 7
using relative references ..................... 11, 12
visual basic toolbar..................................... 9
Menus
adding a macro command ........................ 34
creating from new .................................... 35
deleting macro commands........................ 36
Message Box
adding interactivity................................. 108
buttons .................................................... 109
default button ......................................... 109
definition ................................................ 107
examples................................................. 107
icons ....................................................... 109
interactive use examples ........................ 111
Methods
Activate .................................................... 54
Add ........................................................... 53
arguments ........................................... 53, 54
arguments, examples ................................ 53
Copy ......................................................... 54
definition ............................................ 46, 49
frequently used ......................................... 50
Object Browser ........................................ 68
Open ......................................................... 55
Paste ......................................................... 54
returning ................................................... 52
Select ........................................................ 54
Modules
copying ..................................................... 25
deleting ..................................................... 27
inserting .................................................... 24
renaming................................................... 26
Objects
ActiveCell .......................................... 56, 57
ActiveSheet ........................................ 56, 57
ActiveWorkBook ..................................... 56
Application ......................................... 46, 50
Cells ................................................... 49, 57
collections ................................................ 47
definition .................................................. 46
Page 124
Index
Page 125
Index
HELP SERVICE
Key Training Solutions Limited offers a post-training email Help Service, providing
support for anyone who has a query regarding the content of a desktop training course
they have attended at Key Training.
When is it available?
The Help Service Operates during normal business hours:
Monday to Friday 09:00 - 17:00
To access the help service, send an e-mail to helpservice@keytraining.co.uk
Course Query
It is essential to include the following information in your e-mail so that your query
can be dealt with promptly:
Full title of the course you attended (e.g. Word 2003 Level 1 or
Excel 2007 Level 3, etc).
Please do not send any attachments with your e-mail, (we will request a copy of the
file if required at a later stage)
Course Enquiry
The Help Service is also available if you would like advice on which level of course
yourself or a colleague would be best suited to attend.
You will need to include in an e-mail to the above address:
The application and version you are using or looking to use (e.g. Word 2007).
Please note: We will endeavour to respond to all Help Service requests within 24 hours
of receipt (all requests received on a Friday will be dealt with on the following
Monday).
Key Training Solutions Limited
Page 126