Professional Documents
Culture Documents
VBA Compute PDF
VBA Compute PDF
Microsoft Excel
VBA Programming Introduction
Student Edition
MicrosoftExcel
IntroductiontoVisualBasicfor
Applications(VBA)
StudentEdition
FORCOURSEBOOKINGSANDGENERALENQUIRIES
LONDON (020) 7417 0880
ABOUT KEY TRAINING SOLUTIONS LTD
Key Training Solutions Ltd, one of the largest training organisations in the UK, provides computer
training products and services to help people use software so they can communicate, make decisions,
and solve problems more effectively.
The training materials are for the students' use both during the course and as a reference guide after
the course has been completed.
For more information on what Key Training Solutions may do for you, please visit us at our web site
at www.keytraining.co.uk.
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.
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.
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: Type a name for the macro.
The macro name can contain letter, numbers and underscores
but MUST begin with a letter. The name cannot contain spaces
or punctuation marks
There is a limit of 64 characters to a 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.
Store macro in: 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
The Record Macro dialog box The Record Macro dialog box
(Excel 2000 - 03) (Excel 2007)
Excel window .
9. Perform the actions that you wish the macro to repeat later.
NB If you do not see the Stop Recording toolbar, you can stop
the macro by clicking Tools - Macro- Stop Recording.
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.
The Macro dialog box (Excel 2000 - 03) The Macro dialog box (Excel 2007)
workbook, you will not be able to, and a message will appear explaining how to save it
correctly.
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.
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:
EXERCISE
RECORDING MACROS
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.
11. Format the currently selected cell with a bold font, a blue font colour and a top and
bottom border.
13. Repeat steps 11 and 12 for each cell until you get to the end of the row.
17. Run the FormatHeading macro. If recorded correctly, the macro will format the top
five cells of the table.
Menus and
Toolbar
Project
Explorer
Code
Pane
Properties
Pane
The Project Explorer pane shows at the top level (in bold) all the open Excel files. They
are normally listed as: VBAProject (file name).
Any .XLA files in the Project Explorer pane are Add-Ins that have been installed to
increase Excel functionality. They are normally password protected and cannot be
viewed or edited. Examples of Add-Ins are: FUNCRES.XLA, SOLVER.XLA, and
EUROTOOL.XLA. There may be many more, however, depending on your Excel
setup. ).
Once the file containing the macro(s) has been identified, you need to open its Modules
folder, and finally open the specific module sheet containing the macro VBA code that
you wish to edit. ).
EXERCISE
USING THE VB EDITOR
9. Return to Excel.
11. Open the file, Special Macros. Enable the macros, if prompted.
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.
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...
Procedures
1. Open the workbook containing the macro(s). If the macros are
in the personal macro workbook, it should already be open.
.
3. Select More Commands....
4. Select Macros in the Choose commands from: drop down list.
5. Select the macro that you wish to assign a custom button to in
the list below.
6. Click Add >>.
7. Select the macro name in the list at the right.
8. Click the Modify... button to change the button image, if
desired.
9. Click OK.
10. Click OK.
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.
Discussion
You can assign a macro to a menu. You can choose in which menu you want the macro
to appear. The macro appears as a menu command item to which you can give a
specific name. Whenever the workbook containing the macro is opened, you can
execute the macro, just as you would execute any standard menu command.
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.
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
the right to a convenient position on the
menu bar (eg. between Window and Help).
71. Release the mouse button.
72. Right-click the new menu and type a descriptive name for the
menu in the Name: box (eg. Macros).
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.
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.
The Format Control dialog box The Format Control dialog box
(Excel 2000 - 2003) (Excel 2007)
EXERCISE
ASSIGNING MACROS
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.
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:
SterlingStyle: Ctrl Shift Y
PlainStyle: Ctrl Shift L
NumberStyle: Ctrl Shift N
DateStyle: Ctrl Shift - T
12. Excel 2000 03 users: Add custom buttons to this toolbar to run
the WrapAndCentre and ToggleGrid macros that are stored in
the Personal Macro Workbook.
14. Select the range A4:A10 and run the WrapAndCentre macro
with the custom button.
Excel 2007 users: Remove the custom macro button from the
Quick Access Toolbar.
The Excel Object Model is a hierarchy of objects that you can work with in Excel.
In Excel 2003 there are approximately 200 objects, although about 60 of them are
available only for backward compatibility with previous versions. Every new version
of Excel introduces new ones, and in Excel 2007 there are approximately 250.
A useful link to follow (current at April 2009) if you wish to learn more about the Excel
Object Model is:
http://msdn.microsoft.com/en-us/library/bb149081.aspx
It is not necessary to know all the Excel objects; very effective procedures can be
written for most everyday purposes using only a few. Some of the more common,
user-interface objects are:
Object Refers to
Application The entire Microsoft Excel application.
Workbooks A collection of all the Workbooks that are currently open in the Excel
application.
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)
In Excel 2007 the index number of a workbook can be identified by clicking the View
tab on the Ribbon and clicking the Switch Windows button
Eg:
WorkBooks(1).Activate
or
WorkBooks.Item(1).Activate
(activate the open workbook with an index number of 1)
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
(select the cell A1)
Cells(257).Select or Cells.Item(257).Select
(select the cell A2)
Cells are indexed starting in the top left corner of the worksheet (A1) and going across
the rows and down the columns, hence A1 = Cells(1); B1 = Cells(2), C1 = Cells(3).... etc.
Cells can more easily be used by referencing their row number and column number,
eg:
Cells(1,1).Value = Excel VBA
(enter Excel VBA in cell A1 -row 1 columm1 )
Cells(2,1).Font.Bold = true
(make bold the font in cell A2 - row 2 column 1)
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 Sample Code
Properties (P)
Application Quit (M) Application.Quit
(exit Excel)
ScreenUpdating Application.ScreenUpdating = False
(P) (screen updating is turned off to speed up your macro
code. You won't be able to see what the macro is doing,
but it will run faster)
DisplayAlerts (P) Application.DisplayAlerts = False
(disables Excel from displaying certain alerts and
messages when a macro is running. If a response is
required at any time, Microsoft Excel chooses the default
response. The exception to this rule is Save As where the
default is No but Excel picks Yes to overwrite the existing
file)
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)
ClearFormatting Range(B20).ClearFormatting
(M) (clear cell B20 of just formatting)
Range(A1:D20).PrintOut
(prints just the range A1 to D20 on the current sheet)
a) var1 = ActiveCell.Font.Bold
The value of var1 will be either TRUE or FALSE based on whether the font in the
active cell is bold.
b) var2 = ActiveWindow.Gridlines
The value of var2 will be either TRUE or FALSE based on whether the worksheet
gridlines are turned on or off.
d) var4 = Range(A1:G30).Cells.Count
The value of var4 will be 210, the number of cells in the range A1 to G30.
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:
After argument
Space (2nd) (here left
blank)
Sheets.Add Sheets(1), , 3
Object Method Before Count
argument argument
(1st) (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 third argument is the number of sheets to insert.
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:
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):
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
A full list of arguments for the Open method (Excel 2003) is:
Entering such a long statement would be very time consuming and make for
unwieldy, unnecessarily complicated code that could be difficult to understand and
prone to errors. It is, therefore, usually abbreviated to the object at the lowest level, viz.
Range. Hence, a more concise statement for carrying out the same action would be:
Range(B10).Formula = =B9 * B8
This assumes that you want to enter the formula in cell B10 of the sheet that the macro
is being run from (the active sheet).
If, however, you wish to enter the formula into cell B10 of Sheet2 and you are running
the macro from Sheet1, then you have to go up the hierarchy to make the statement
more specific, eg:
Sheets(Sheet2).Range(B10).Formula = =B9 * B8
This assumes that you want to enter the formula in cell B10 of the workbook that the
macro is being run from (the active workbook).
If, however, you wish to enter the formula into cell B10 of Sheet2 of another open work
book named, Stock Report, then you have to go up the hierarchy further to make the
statement even more specific, eg
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 The workbook ActiveWorkbook.Save
from which
ActiveWorkBook.PrintOut
the macro is
being run. ActiveWorkbook.Close
variable = ActiveWorkbook.FullName
ActiveSheet The sheet from ActiveSheet.PrintOut
which the
ActiveSheet.Delete
macro is being
run ActiveSheet.PageSetup.Orientation =
xlLandscape
variable = ActiveSheet.Item
ActiveCell The cell that is ActiveCell.HorizontalAlignment = xlCenter
currently
ActiveCell.RowHeight = 20
selected
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.
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
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
Sub SetUpNewReport
or
Sub Set_up_new_report
Sub SetUpNewReport ()
End Sub
The brackets are used for passing arguments to a sub procedure from a
called sub procedure, a topic that is outside the scope in this course. In most
cases the brackets are left empty.
End Sub indicates where the sub procedure ends and must, obviously, be kept
as the final line of the sub procedure.
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;
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.
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.
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: .
A useful general-purpose block is the With ... End With block. This allows you to
perform a series of statements on a specified object (and/or associated property)
without having to retype it repeatedly. Not can this improve performance, but also
reduces the risk of typos. Think of a With block a bit like using ditto in normal
written communications.
Consider the following code that enters and formats a title into cell A1:
Sub AddReportTitle ()
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
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
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) Offset(0 , 1)
Same row, left one Cell being referred to Same row, right one
column 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): .
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.
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:
The window is essentially telling you that the sub procedure had to stop at a certain
point, because it encountered an unexpected condition. The Run-time error number
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.
Procedures
3. Click the Continue button if you believe that the error has
been successfully edited.
Procedures
1. Launch the VB Editor.
EXERCISE
WRITING SUB PROCEDURES
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.
8. The next group of statements must format the active cell with:
A font size of 18
A font name of Arial Black
A font colour of Blue
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
A cyan interior colour
14. The final statement of the sub procedure must select cell A1
17. Save the Regional Sales workbook then exit Excel and save the
Personal Macro Workbook, if prompted.
Symbol Operator
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
If the test is false, nothing specific will happen and any following code is NOT
dependant on the test. For example:
In the single line form, multiple actions can be performed but the code becomes
long and complex to read. A colon (:) must be used to separate the actions, the
syntax is as follows:
2. Block Form
This syntax is more flexible and clearer to read when there are multiple actions to
perform if the test is true. If the test is false, nothing happens. Note the use of End
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:
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:
A test can be elaborated further by adding And and/or Or conditions to it. The syntax
is as follows:
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.
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.
Any code following this will be executed irrespective of whether the test is true or
false.
Because the single-line form can become very long and difficult to read, the block form
is preferable in almost all cases:
If <test> Then
<actions if true>
Else
<actions if false>
End If
Any code following the End If will be executed irrespective of whether the test is true
or false.
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.
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.
If <test1> Then
<actions if true>
ElseIf <test2> Then
<actions if true>
Else
<actions if false>
End If
In the example below, the font in the active cell is made blue if it contains a value of
Status A.
If, however, the active cell does not contain Status A, control is passed to the ElseIf,
which carries out a second test to establish if it contains the value Status B. If this is
true then the font in the active cell is made green.
If the active cell does not contain Status B either, then control passes to Else and
under all other circumstances makes the font red.
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.
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.
A single expression is evaluated at the top of the Case structure. Each case is then
checked for this value, and the appropriate statements executed. Control is then passed
to the statement after the End Select statement. If no Case statement holds the
evaluated value, then the statements after the Case Else are executed.
Case Else is optional.
In the example below, the font in the active cell is made blue if it contains a value of
Status A
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.
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.
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.
1. Start of Loop
(tells the sub procedure how often to repeat the statement(s) that follow(s))
2. Statements
(the actions to perform a certain number of times)
3. End of Loop
(tells the sub procedure to return to the start of the loop and check whether it has
carried out the statements a sufficient number of times)
In this lesson, the DO loop is examined. FOR loops are discussed and demonstrated
separately on page 96.
A DoLoop is used to run a block of statements until a condition is True or while a
condition becomes True. It comes in two forms Do Until and Do While. In the
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.)
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...)
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:
2. Move across a row of data until the cell is found containing todays date:
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. eg. ActiveCell.Value = or ActiveCell.Offset(0,1) <>
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.
EXERCISE
DECISIONS-MAKING CODE AND DO LOOPS
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
An object (although this is not covered on this course)
Variables can also help make your sub procedures more interactive. Consider the
following statement that opens an Excel file:
Now consider the following where cell A1 contains the text, Sales Data.xls:
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.
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.
Most punctuation marks (eg. , . : ; ? -) and special characters (eg. $, %, ^, &, #, })
cannot be used.
A variable name can be no longer than 250 characters.
Assigning a value to a data variable can be done by:
1. Assigning a value from a cell on a worksheet.
celVal = Range(A1).Value Assigns the value in cell A1 of the active sheet to
the variable celVal.
celVal would, therefore, be a piece of text (a
string) or a number. If cell A1 were empty, then
celVal would store an empty string (viz.
nothing!).
myNum = Cells(3,4).Value Assigns the value in cell that is at the intersection
of row 3 and column 4 of the active sheet(ie. D4)
to the variable myNum.
myNum would, therefore, be a piece of text (a
string) or a number. If cell D4 was empty, then
myNum would store an empty string.
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 Stores the number 10 in the variable
secNum = 20 firstNum; stores the number 20 in the
variable secNum and stores their product in
thirdNum = firstNum * secNum the variable
MsgBox thirdNum. thirdNum.
Displays the variable
thirdNum in a
message box.
fileToUse = InputBox(Enter the Prompts the user to type a file name and
name of the file to open) then opens it.
WorkBooks.Open (fileToUse)
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.
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.
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: .
Unless otherwise specified, undeclared variables are assigned the Variant data type.
If a data type is not specified, eg.
... the variable will default to a variant data type. This data type makes it easy to write
sub procedures, but it is not always the most efficient data type to use. Because the sub
procedure does not know what you are going to put into a variant variable, it may
create an unnecessarily large space in the computers memory with a resulting loss of
performance.
You should consider using appropriate data types if:
Your program is very large and uses many variables.
Your program must run as quickly as possible.
You write data directly to random-access files.
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 -3.402823E38 to -1.401298E-45 for negative values;
1.401298E-45 to 3.402823E38 for positive values
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 January 1, 100 to December 31, 9999
String 10 bytes + 0 to approximately 2 billion
(variable-length) string length
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.
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.
EXERCISE
TO ASSIGN VALUES TO VARIABLES.
The structure repeats the statements a number of times depending on the values of
start, end and step.
Variable is a made-up name (naming rules apply see page 87), which holds a number,
the variable name is set to equal start, and each time the statements are run, the
variable name increments by the value of step. If step is omitted then, the increment
will default to one. For example, the following loops through the statement 6 times,
creating random numbers between 1 and 49 in a column.
For counter = 1 To 6
ActiveCell.Value = Rnd * 49 (Rnd is a VBA function that returns a
value less than 1 but greater than or
equal to zero. It is equivalent to the
=RAND() Excel worksheet function.)
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.
numCells = Selection.Cells.Count
For counter = 1 To numCells
ActiveCell.Value = ActiveCell.Value * 2
Next counter
The real power of the For... Next loop comes by using the value of the variable within
the loop.
The following example shows code that loops 100 times (1 To 100). The first time
round the loop, the value of the variable (i) will be 1; the second time round the loop
its value will be 2, the third time 3, etc.... The statements within the loop, therefore,
will make use of the variable to identify cells (using Cells) and put a value into them.
The result of this is that starting in cell A1, the loop will fill the Range A1 to A100
with consecutive numbers starting at 1.
Dim i as Byte
For i = 1 To 100
Cells(i , 1).Value = i
Next i
The following example creates a variable named wBkCount that counts the number
of open workbook. It then uses the variable (i) in a For... Next loop to save them all.
wBkCount = Workbook.Count
For i = 1 To wBkCount
WorkBooks(i).Save
Next i
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.
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.
The For... Next loop does not necessarily have to start counting from 1, it can start at
any value including negatives. Eg.
The For... Next loop, however, will fail if the start number is higher than the end
number, eg. For counter = 100 To 1.
This begs the question: What is a collection (or array) and how do we define an
element in it?
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 loop works rather like a check sheet, where each cell gets ticked as done once the
statement(s) have been executed on it.
The order in which the elements are ticked starts with the cell in the top left corner
and continues from left-to-right along the top row. It then repeats from left-to-right
going down the columns.
The following example uses a For Next...Each loop to enter a zero into any blank cells
in the range B2 to D200.
Note how the variable defined in the first line MUST be used as the object in the
repeating statements. If ActiveCell had been used, the statements inside the loop
would have been ignored and the If block executed on whichever cell was active
when the macro was run.
The For Each ... Loop is more powerful that the Do loops and even (to an extent) the
For Next loop.
It is faster because there is no physical selecting of objects, it is all done in the
computers memory.
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.
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.
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.
EXERCISE
CREATE A FOR LOOP STRUCTURE.
To use the message box function purely to display a message, it is only necessary to use
the prompt argument, eg. :
Embellishments can be added to the message box by adding an icon and a window
title, eg.
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
The buttons argument consists of constants or values from each of the following three
groups:
Icon style:
Constant Value Display Icon
Default Button:
Constant Value Default
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 third button is default
The buttons argument of the message box function can hold three pieces of
information separated by a plus (+) symbol. Using the following code as the buttons
argument will produce Example C below.
vbQuestion
vbYesNo vbDefaultButton2
(second from left)
A more concise method of writing the above sample of code would be to use the
numeric values for the arguments, eg.
4 + 32 + 256
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 If you dont wish to add an icon
and/or default button to the and/or a default button to the
message box, type a plus message box, go to 15 below.
symbol (+).
12. Type the necessary value to
indicate which icon to
display, eg. vbQuestion
13. Type a plus symbol (+).
In the following example, the message box offers a yes/no response. If the user clicks
yes, then the procedure will delete all the data from the sheet. If the user clicks no, the
procedure will terminate.
If MsgBox (Do you want to delete all data, vbYesNo + vbCritical) = vbYes Then
ActiveSheet.Cells.Clear
End If
The result of the message box (ie. whether the yes or no button is clicked) can be stored
in a variable and the code could also be written:
Procedures
1. (The procedure below assumes a message box containing Yes
and No buttons. It can be adapted, however, to respond to any
set of buttons (eg. vbOKCancel, vbRetryCancel etc.))
2. Position the cursor in the sub procedure code where you want
to place the statement.
3. Create an interactive message box as described in the previous
topic of this lesson.
4. Press Enter.
5. Type If.
6. Type a space.
7. Type the variable name that you have used to store the
response from the message box.
8. Type a space.
9. Type = vbYes.
10. Type a space.
11. Type Then.
12. Type the statements that you want the sub procedure to
perform if the user has clicked the Yes button.
13. Press Enter.
14. Type Else.
15. Press Enter.
16. Type the statements that you want the sub procedure to
perform if the user has clicked the No button.
17. Press Enter.
18. Type End If.
19. Press Enter.
20. Add additional code as necessary.
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.
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
ActiveSheet.Name = shtName
Or...
Sample B Prompts user for two inputs, carries out a calculation and returns the result
in a message box and in cell A1.
Or...
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 If you dont wish to add a
input box, type a comma title to the input box, go to
14 below.
11. Type a speech mark (Shift 2).
12. Type the title text.
13. Type a speech mark (Shift 2).
14. Type a comma.
15. If you wish to add default text If you do not wish to add
to the input box, type a comma default text to the message
box, go to 19 below.
16. Type a speech mark (Shift 2).
17. Type the default text.
18. Type a speech mark (Shift 2).
19. Type a comma .
20. If you wish to specify an x and If you do not wish to specify
y position for the message box, an x and y position for the
type a comma. message box, go to 24 below.
21. Type a value for the x position.
This is measured in Twips and
there approx. 10 Twips to a
pixel. The x position is
measured down from the top
left-hand corner of the Excel
window.
22. Type a comma.
23. Type a value for the y position.
This is measured in Twips and
there approx. 10 Twips to a
pixel. The y position is
measured to the right from the
top left-hand corner of the
Excel window.
24. Type a closing bracket ) .
25. Press Enter.
26. Add additional code as necessary.
EXERCISE
USING INTERACTIVITY
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.
9. Run the macro to check that the procedure works, entering some
made up information of your own into each input box.
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 Unsigned macros are automatically disabled and the file is opened.
With signed macros, the source of the macro and the status of the
signature determine how signed macros are handled.
When attempting to open a workbook containing macros, no
message will appear.
Medium With unsigned macros, the user is prompted to enable or disable
the macros. When attempting to open a workbook containing
unsigned macros, the following message will appear.
With signed macros, the source of the macro and the status of the
signature determine how signed macros are handled.
Low When security it set to low, all macros are treated equally
regardless of origin or certificate status. With low security, you
receive no prompt or signature validation and macros are
automatically enabled.
Use this setting only if you are certain that all macros in your files
are from trusted sources.
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.
Disable all macros with With unsigned macros, the user is prompted to
notification (default) enable or disable the macros.
Disable all macros except With signed macros, the source of the macro
digitally signed macros and the status of the signature determine how
signed macros are handled.
Enable all macros When security it set to low, all macros are
treated equally regardless of origin or certificate
status. With low security, you receive no
prompt or signature validation and macros are
automatically enabled.
Use this setting only if you are certain that all
macros in your files are from trusted sources.
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
INDEX
Coding description .................................................. 8
ActiveCell ................................................. 57 naming ........................................................ 7
capitalisation ............................................. 60 opening ............................................... 13, 16
comments .................................................. 60 personal macro workbook .......................... 7
concatenation character ............................ 62 recording .................................................... 6
indentations............................................... 60 running ..................................................... 10
line breaks ................................................. 61 saving ................................................. 12, 13
Run-time error .................................... 65, 66 security warnings Excel 2000 - 03 ........... 14
Selection ................................................... 56 security warnings Excel 2007 .................. 14
statements, definition ................................ 59 shortcut key ................................................ 7
sub procedures, definition......................... 58 storing......................................................... 7
the OFFSET function................................ 64 using relative references ..................... 11, 12
white space ............................................... 60 visual basic toolbar..................................... 9
With... End With block ....................... 62, 63 Menus
Control Structures adding a macro command ........................ 34
Do Loop .............................................. 81, 82 creating from new .................................... 35
ElseIf................................................... 77, 78 deleting macro commands........................ 36
For Each examples.......................... 101, 102 Message Box
For Each loop ........................... 99, 100, 103 adding interactivity................................. 108
For Next examples .............................. 96, 97 buttons .................................................... 109
For Next loop ...................................... 96, 98 default button ......................................... 109
If...Then .................................. 73, 76, 78, 80 definition ................................................ 107
If...Then...Else .......................................... 76 examples................................................. 107
nested For Each examples ...................... 103 icons ....................................................... 109
nested For Each loops ............................. 103 interactive use examples ........................ 111
nested For Next examples......................... 99 Methods
nested For Next loops ............................... 99 Activate .................................................... 54
Select Case.......................................... 79, 80 Add ........................................................... 53
using Step with For Next .......................... 97 arguments ........................................... 53, 54
Input Box arguments, examples ................................ 53
definition................................................. 113 Copy ......................................................... 54
examples ................................................. 113 definition ............................................ 46, 49
Keywords frequently used ......................................... 50
End Sub .................................................... 58 Object Browser ........................................ 68
Sub ............................................................ 58 Open ......................................................... 55
Macro buttons Paste ......................................................... 54
copying ..................................................... 39 returning ................................................... 52
creating ..................................................... 37 Select ........................................................ 54
creating in Excel 2000 - 03 ....................... 37 Modules
creating in Excel 2007 .............................. 38 copying ..................................................... 25
deleting ..................................................... 42 deleting ..................................................... 27
moving ................................................ 40, 41 inserting .................................................... 24
sizing................................................... 40, 41 renaming................................................... 26
using ......................................................... 37 Objects
Macros ActiveCell .......................................... 56, 57
assigning a shortcut key ............................ 30 ActiveSheet ........................................ 56, 57
assigning to a menu .................................. 34 ActiveWorkBook ..................................... 56
assigning to a toolbar button ..................... 31 Application ......................................... 46, 50
defining ....................................................... 6 Cells ................................................... 49, 57
deleting custom button.............................. 36 collections ................................................ 47
deleting from a menu ................................ 36 definition .................................................. 46
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).
As much information as possible regarding the problem or query to be solved.
Your contact details (including best time for us to contact you).
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).
Your telephone number.
Your company name.
The best time for us to contact you.
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).