Vous êtes sur la page 1sur 87

Excel Data Entry Tips and Techniques

[Ctrl]-[Home] takes you to A1

[Ctrl]-[End] takes you to the last data cell in your worksheet

Move to next sheet [Ctrl]-[PgDn]

Move to previous sheet [Ctrl]-[PgUp]

The VCR buttons to the left of the sheet tabs let you navigate through
sheets.
You can right-click on the VCR buttons and from the resulting menu select
the sheet you want to view.

To move to the next window (open workbook) [Ctrl]-[Tab]

Tools | Options | Edit tab has a dropdown for specifying the direction the
cell pointer moves when tapping [Enter] after entering data in a cell.

The Status Bar, at the very bottom of the screen usually says Ready in the
lower lefthand corner. It provides useful information. One useful feature is
that when a block of cells is selected the SUM of the cells will appear in the
Status Bar. Right-click the SUM in the Status Bar and you can choose
another function to apply to the selected cells. You cant do anything with
this result, however, except view it in the Status Bar.

Window | Split or Window | Freeze Panes will divide the window above and
to the left of the current cell pointer position. This will allow column and/or
row headers to remain displayed in one section of the window while you
scroll and move through data in another section of the window.
You can also split the window by dragging the little gray bar above
the up arrow in the vertical scroll bar and/or the little gray bar to the
right of the right arrow in the horizontal scroll bar.

Selecting Cells

Holding [Ctrl] while using mouse selection lets you select a noncontiguous block of cells

Click the mouse once in the upper lefthand corner cell of a block of data
you want to select, then hold the [Shift] key down when you click the
mouse on the cell that defines the lower righthand corner of your block

Use the keyboard [Shift] combined with any keyboard movement


selects
[Shift]-arrows
[Shift]-[Ctrl]-arrows

Select the current block of data [Ctrl]-*

Once youve selected a block of cells, pointing at the border of the


selection will turn the mouse pointer to an arrow, this is the move cursor.
To move cells, click and drag, clicking when you have the move
cursor/arrow.
If you hold [Ctrl] before click-drag moving cells, you can copy the cells.

Entering Patterned Data

Type the first two values in a sequence, select the two cells, click and drag
using the Fill Handle to extend the pattern
If you right-click and drag with the Fill Handle, when you release the
mouse youll be presented with a list of options for the type of
pattern/sequence you want to use.

Select a block of cells (contiguous or noncontiguous), type the value to


enter, [Ctrl]-Enter will put that value in all the selected cells

Use a formula and then once all the data is entered, select the results, use
Edit | Copy, click in the upper lefthand corner of the destination, and use
Edit | Paste Special as Values

If youd like to randomize your data, one option is to create a column of


random numbers using the RAND() function and then sort your data with
the random number column as your sort field.

Excel Functions

The IF function is frequently useful

IF(CONDITION, action or value if CONDITION is true, action or value if


CONDITION is false)

If you have standard text to enter, maybe one of 5-10 possible entries, maybe
using the INDEX function would help.

List of possible values in E1:E9

If you want the first value, you enter 1 in B1, 3rd value in the list,
enter 3,

Copy this formula down Column C =INDEX($E$1:$E$9, B1)

Once you have the values you want in Column C, Add a column, and
then use Copy | Paste Special | Values to copy the formula results to
your new column

MATCH provides the complimentary operation for INDEX given a value you
want to find, look it up in an array of possible values, and return the index number
for that values location in the array.

MATCH (location of possible values, lookup value, match type)


If match_type is omitted, it is assumed to be 1.
If match_type is 1, array of values must be sorted in ascending order
and
MATCH finds the largest value that is less than or equal to
lookup_value.
If match_type is 0, MATCH finds the first value that is exactly equal to
lookup_value. Lookup_array can be in any order.
If match_type is -1, array of values must be sorted in descending
order and
MATCH finds the smallest value that is greater than or equal to
lookup_value.

The INDEX function technique above can be combined with List Box or Combo
Box tools from the Forms (or Control Toolbox) toolbar.

Once youve added your List Box or Combo Box the key is to rightclick the Box and choose Format Control

In the Control tab you specify (using the example above), Input
Range: $E$1:$E$9

Choosing a value from the list will populate the cell specified in Cell
Link, say: B1

Youd still have to convert this number to a value in another column


using the INDEX function discussed above.

The List Box or Combo Box will only populate one cell with a value.

If you need to calculate or dynamically enter a cell reference for a formula,


INDIRECT is a useful function. SUM(INDIRECT(A&D5):A15) would
concatenate A with the row number specified in D5 and sum in column A from that
row through A15.

Close relatives of the INDEX function are VLOOKUP, HLOOKUP, and LOOKUP
For Example:

The lookup table of the INDEX example would be extended to two


columns.

Column D would number the values in Column E, that is, Column D


contains the numbers 1 through 9.

In Column B you enter the number of the value you want to pick
from the lookup table.

Column C contains the formula: =VLOOKUP(B1,$D$1:$E$9,2)


This translates to ==> Lookup the value in B1 in the first column of
the table in $D$1:$E$9, find the value in a row in the table, return the
value in the 2nd column of the table.

Formatting

Format | Conditional Formatting might be useful for error checking (invalid values
could show up formatted in red)
If you have multiple conditions specified, the conditions are evaluated
from the top of the list. Once the cell satisfies a condition it applies that
formatting and doesnt continue down through the rest of the possible
conditions.

To find cells that are formatted with Conditional Formatting use Edit | Go To |
Special and choose the Conditional formats radio button. To find cells with

identical conditional formats to the selected cell,click Same below Data


validation. To find cells with any conditional formats, click All below Data
validation.

Tools | Options | Calculation | Precision as Displayed checkbox could prevent


you from falling into a potentially embarrassing rounding error situation

Want to transpose your columns to rows or rows to columns? The transpose


feature in Office 97/2000 is in the Edit | Paste Special dialog box.
1.

Select the cells to transpose, Edit | Copy

2.

Right-click on the upper-lefthand corner of a range of empty cells


that can accommodate the transposed result.

3.

Choose Paste Special and check the transpose checkbox

Selecting cells and tapping the Delete key only deletes the cell contents,
equivalent to Edit | Clear | Contents

Edit | Delete chops out the cell and asks you how youd like to fill
in for the missing cells

Edit | Clear | Formats will let you delete the formatting of the cell,
e.g., borders, fonts, numeric formatting,

2 There may be certain portions of the worksheet that youd like to protect from any

possible changes. By default all the cells in the worksheet are locked but the locks
are ignored. Tools | Protection | Protect Sheet activates recognition of the locks.
Before using Protect Sheet you would unlock all the cells you want to be able to
edit when the rest of sheet is protected Select Cells, Format | Cells | Protection
tab and uncheck the default lock. Then use Tools | Protection | Protect Sheet.
If most of your cells are going to be unprotected with just a few protected
1.

Use [Ctrl]-A to select all the cells in the sheet

2.

Format | Cells | Protection tab and uncheck the default lock

3.

Select the cells you DO want to protect

4.

Format | Cells | Protection tab and CHECK the lock back on

5.

Tools | Protection | Protect Sheet

Miscellaneous

Electronic Post-It notes might be useful to make comments on your


worksheet, Insert | Comment.
Options for printing comments with the sheet are in: File | Page Setup |
Sheet | Comments option dropdown

Data | Text to Columns is a useful tool for separating into multiple columns
text that is currently contained in one column. For example, maybe you
have social security numbers in column A and you just need the last four
digits of the SSN. Data | Text to Columns would let you separate the SSN
into two columns.

Sometimes you may want to combine into one column text that is
currently contained in two columns. One way to do this is to write a
formula in a third column which uses the concatenation operator, the
ampersand. This formula in C1 would return the contents of A1 followed
by the contents of B1: =A1&B1
If you want to include a literal character, say a space, use the
form: =A1& &B1

The Wizard used in Data | Text to Columns is the same tool you have
available for opening text files you want to import into Excel. File | Open
with some text file will bring you to Step 1 of the Data Import Wizard.

Use File | Page Setup | Page tab | Fit to checkbox if your printout is
extending just beyond one page

To move or copy an entire worksheet to a new workbook:


1.

Open the original workbook and choose Edit, Move Or Copy Sheet

2.

When the Move Or Copy dialog box opens, click the arrow at the
right side of the To Book list box. Choose New Book from the list.

3.

If you want to copy the sheet, select the Create A Copy check box
and click OK.

4.

Excel moves or copies the selected sheet to a new workbook.

Sometimes codes used in data entry need to be sorted in some order that
is not alphabetical or numeric. You can define a custom sort order in Tools |
Options | Custom Lists. Rather than Adding the list, the easiest way to
enter the values is to Import list from cells. To use your list, Data | Sort |

Options button has a dropdown where you can choose your list for the sort
order.

How to Create a Drop Down


List in Excel?
Having a drop-down list in your Microsoft Excel spreadsheet can often improve the
efficiency of your data entry, while also limiting data entry to a specific set of items or
data made available in the drop-down list.
Drop-down lists can greatly facilitate data entry. Heres a look at how to use
Excels data validation feature to create handy lists within your worksheets.
In Access, you can limit user entries by forcing users to choose a value from a
list control. Office applications use the same functionality in built-in drop-down
lists. For instance, the Highlight and Font Color controls on most Formatting
toolbars use this flexible tool. Simply click the small triangle to the right of the
icon to display a list of choices.
You can create the same type of control for your users in an Excel sheet, but the
process isnt intuitive. The option is in the Data Validation feature. Fortunately,
once you know the feature exists, its easy to implement. You need only two
things: a list and a data entry cell. The following sheet shows a simple dropdown list in an Excel sheet.

Users click the drop-down arrow to display a list of items from A1:A4. If a user
tries to enter something that isnt in the list, Excel rejects the entry. To add this
drop-down list to a sheet, do the following:
1.

Create the list in cells A1:A4. Similarly, you can enter the items in a single
row, such as A1:D1.

2.

Select cell E3. (You can position the drop-down list in most any cell or
even multiple cells.)

3.

Choose Validation from the Data menu.

4.

Choose List from the Allow options drop-down list. (See, theyre
everywhere.)

5.

Click the Source control and drag to highlight the cells A1:A4. Alternately,
simply enter the reference (=$A$1:$A$4).

6.

Make sure the In-Cell Dropdown option is checked. If you uncheck this
option, Excel still forces users to enter only list values (A1:A4), but it wont
present a drop-down list.

7.

Click OK.

You can add the drop-down list to multiple cells. Select the range of data input
cells (step 2) instead of a single cell. It even works for noncontiguous cells. Hold
down the Shift key while you click the appropriate cells.
Its worth noting that the drop-down arrow is visible only when the cell is active.

10 Crazy Excel Tips & Tricks


You Must Know!
10 Excel Tips and Tricks which are Incredibly Easy, Quick & Handy:

Automatically SUM () with Alt + =: Did you know you could add an
entire row or column by simply clicking the first empty cell? Click, press ALT
+ = and simply add up the numbers in every above cell.

Number Formatting Keyboard Shortcuts format: There is a true logic


behind the keyboard shortcuts, which otherwise seem random to you. For
example, to format a number as a currency you have to use the keyboard
shortcut CTRL + SHIFT + 4. It may seem random to you, but SHIFT + 4
gives you a $ sign. So if you want to format a currency, you simply put
CTRL + $. You can do the same with formatting a number as percent

CTRL + to display formulas: While in the process of misbehaving


troubleshooting numbers, have a go at the formulas first. See the formula
used in the cell by simply hitting the two keys: Ctrl + (also called the
acute accent key) which is the furthest to left on the row with number keys.
It is tilde (~) when you press shift.

Excel Tips & Tricks for a Successful and Efficient Data Analysis

Go directly to the Start and End of Column Keyboard: Sometimes,


data sets are bottomless pits. You could scroll till the end of eternity or use
the shortcut CTRL + down arrow to jump down the last filled cell or viceversa.

Repeat the same formula for multiple cells: Typing the same formula
for all cells, No! First you need to create the formula in the first cell, and
then take the cursor to the right lower corner of the cell. See the cursor
turning into plus? Now simply double click to copy the formula and drag it
on the rest of cells in the column. Bingo, problem solved!

Delete/Add columns keyboard shortcut: It takes you all day to


manage columns and rows in your spreadsheet. Heres how you save a
little time: Press CTRL + minus and it will delete the column you have
placed your cursor on and CHTRL + Shift will add a new column.

List of Excel Keyboard Shortcuts By Category

Adjusting width of column(s): Theres a way to get rid of those useless


#### entries. Simply click on the column header and move it on to the
right side. Double click when the cursor becomes a plus sign and your work
is done.

Copying a number or date pattern: This one is damn easy! Enter the
information in two rows to establish the pattern. Highlight those and drag
your cursor down to the number till which you want your cells to fill up
respectively. This will work with numbers, dates and months.

Tab between worksheets: So cross-checking different worksheets every


time means you have to touch the mouse and all that. Why dont you
simply enter CTRL + PGDN and if you want to go reverse type CTRL +
PGUP.

Double clicking format painter: With a simple mouse click, you can
now duplicate a format in other cells with only a click. Many excel users
use it by double clicking on the format painter to copy the format into
multiple cells. Yay!

7 Simple Tricks to Make Smart and Neat Excel Graphs


So these were some amazing excel tips that are deemed to come extremely handy in
times when you need to save even an itsy amount of time. It is always easier when you
make your data easier to manage.
aking the time to learn some Excel tips and tricks will likely help you boost your
productivity and streamline your spreadsheets.
We previously shared some Excel insights. Here are five more tips to consider:
1. Use Number Formatting Shortcuts
For circumstances when you need to format a large amount of data, Excel offers timesaving shortcuts for many common formatting functions. Experiment with these handy
ones:

Format numbers to include two decimal places: Ctrl+Shift+1

Format as time: Ctrl+Shift+2

Format as date: Ctrl+Shift+3

Format as currency: Ctrl+Shift+4

Format as percentage: Ctrl+Shift+5

Format in scientific/exponential form: Ctrl+Shift+6

Also Read: Complete List of Keyboard Shorcuts By Category


2. Use Sparklines to Display Data
Sparklines are a built-in feature of Excel 2010, Excel 2011 for Mac and Excel 2013 that
allow you to display small charts inside cells. These can be line charts, bar charts or
simple win/loss charts. To create a Sparkline chart, select the range of numbers youd
like to include, click the Insert menu, then choose one of the chart options. Select a
location range, which must be located along a single row or column in the same

worksheet as your data range. Sparklines can help you easily display trends in your
data in a compact format.
Also Read: 10 Simple Tips To Make Your Excel Charts Sexier
3. Manipulate Data with Pivot Tables
When you have a large, detailed data set, pivot tables allow you to easily manipulate
your data. These tables are interactive and can help you analyze data, detect patterns
and make comparisons. Creating a pivot table is as easy as using the built-in PivotTable
and PivotChart Wizard, located in the Data drop-down menu. The wizard helps you
choose the data to include in your PivotChart and format that information in a
meaningful manner. For more information on creating pivot tables, refer to
this PivotTable Tutorials.
4. Move Between Formulas and Results
To efficiently switch between the cell data and formula, use the Ctrl+tilde (~) keystroke.
This allows you to rapidly check formulas when working in a large spreadsheet.
5. Hide Zero Values
Hiding zero values can be helpful within large data sets by allowing you to see data
more clearly. To hide zero values, you simply need to change the options in your Excel
setup. Navigate to this function by clicking the File drop-down menu and choose
Options. Then choose Advanced from the left-hand menu and uncheck the box for
Show a zero in cells that have zero value. (Mac users: Go to the Excel drop-down
menu and choose Preferences, then uncheck Show zero values.)

5 Tips for Data


Manipulation in Excel
If your work with data much, you dont need a statistical model to predict that the odds
of consistently getting data in the format you need for analysis are pretty low. Those
who do a great deal of data cleaning and reformatting often turn to scripting languages
like Python or specialty tools such as OpenRefine or R.

But it turns out that theres a lot of data munging you can do in a plain old Excel
spreadsheet if you know how to craft the proper formulas.
In a presentation at the recent 2014 Computer Assisted Reporting (CAR) conference,
MaryJo Webster, senior data reporter with Digital First Media a newspaper group in
New York shared some of her favorite Excel tricks. The goal of these tips, Webster
said: Learn at least one new thing that will make you say, Why didnt I know this
before?
Date functions
Tip 1: Split dates into separate fields
You can extract the year, month and day into separate fields from a date field in Excel
by using formulas =Year(CellWithDate), =MONTH(CellWithDate) and
=DAY(CellWithDate). Splitting dates this way by year, month and day of month
works in Microsoft Access as well, Webster said.
In addition, you can also get the day of the week for any date in Excel with
=WEEKDAY(CellWithDate). The default returns numbers, not names of the days of
week, with 1 for Sunday, 2 for Monday and so on.
To display the name of the weekday instead of a number, apply a custom format to the
cells with the weekday numbers, using Format cells > Custom; then type ddd in the
Type text box to get three-day abbreviations or dddd for the full day name.
Tip 2: Find someones current age
If you have someones date of birth, you can find his or her current age on whatever
day you open the spreadsheet with the =DATEDIF() and =TODAY() functions. TODAY(),
as you might guess, gives the current date. DATEDIF() gives the difference between two
dates in units of years (y), months (m) or days (d), using the syntax:
=DATEDIF(Date1, Date2, Unit of measure)
So, to get current age in years, use the formula:

=DATEDIF(CellWithBirthday,TODAY(), y)
Note that the years unit returns ages in whole numbers and does not round up.

Reshaping data

Tip 3: Create multiple rows out of only one


Sometimes you need data in a format with one row for each observation, but what you
already have comes with multiple observations for each row instead. In Websters
example of Affordable Care Act Exchange plan pricing, there is a column for prices in
each age group: 1-20 years old, 21 years old, 22 years old and so on. However, some
visualization and analysis tools require one rowfor each plan/price combination,
not one row with multiple prices.

Sometimes you need data in a format with one row for each observation, but what you already
have comes with multiple observations for each row instead. Heres one way to resolve it.
Tableau visualization software is one such tool that needs one data point per row, not
multiple data points per row, so the vendor created a Tableau Reshaper Tool that
works with recent versions of Excel on Windows.
You can download this free tool from the Tableau website. Although one add-in says
its for Excel 2010, it worked fine with Excel 2013 on my Windows 8 PC.

Several CAR attendees said theyve spent hours reshaping large data sets by manually
cutting and pasting, and the free Tableau tool will save them a lot of time. You dont
need to have other Tableau software installed on your system to use it.
The columns youre keeping as row ID columns should be placed on the left, and all
your data columns on the right. To use the reshaper tool, put your cursor on the first
cell with data that you want transformed. Then go to the Tableau menu and choose
reshape data. Say OK. You can watch a brief example below.

Tip 4: Create more easily sortable data


Another common data format problem is when you get a spreadsheet thats less like
a sortable table of data and more like a Word document with column headers. One
example: a spreadsheet with the name of a team on one row followed by all the
players on that team, then the name of another team right below followed by the
players and so on. Its difficult to analyze a worksheet where column headers are
interspersed with data, since you cant easily sort, filter or visualize data by team.
One way to deal with this is to add a new column with the team name for each player.

Its difficult to analyze a worksheet where column headers are interspersed with data, since you
cant easily sort, filter or visualize data by team. One way to deal with this is to add a new
column with, in this case, the team name for each player.

The trick is that you need to have a pattern to follow, according to Webster. In the
example above, the position column is empty for the team name rows but filled in for
the player rows. By filling in just the first cell with the team name manually, you can
then use this formula to automatically fill in the rest:
=IF(B3="",A3,C2)

That says: If cell B3 is blank, fill in the value of the cell in the first column of the same
row (in this case A3). Otherwise, fill in the value from the cell thats just above it (in this
case C2, which should be the team name from the row above for all the player rows).
Make sure to start with the first player row after having manually entered the first
header row.

Search and replace


Tip 5: Create a new column
You probably know that you can do a search and replace in Excel with a typical texteditor control-F find-and-replace. But did you know that you can also create an entirely
new column in Excel based on search-and-replace on an existing column? That needs
the =SUBSTITUTE function, using the syntax:
=SUBSTITUTE(CellWithText, "oldtext", "newtext")

And for lots more on getting the most out of Excel:

Excel VBA Tutorial Part 1 - VBA Code Presentation


When learning to produce VBA code, it is important, from the very
start, that you adopt good habits in terms of code presentation, so
that it is easy to read the code and understand how it works.
While you may, at the time you are writing the code, have a clear
idea of what it does and how it works, you need to consider what the
code will look like when you return to it in 6 months' time. Worse

still, what if someone else needs to work on your code and has to
figure out how it works?
This page discusses comments, code indentation and line breaks all
of which will assist in making your code clearer and easier to
interpret.
Comments

The single most important practice for writing clear, decipherable


code is to add frequent comments.
Comments are lines in your code which act as notes to yourself or
others, to explain what the code means or what it is doing.
Comments are not executed during the running of the program, so
have no impact on the result your macro. VBA considers any line
that starts with an apostraphe (') to be a comment and the Excel
VBA editor highlights these lines by colouring them in green, so you
can see, at a glance, that they are comments and will not be
executed.
See the example below, which shows comments used to clarify the
details of a simple Sub procedure:

' Sub procedure to search cells A1-A100 of the current active


' sheet, and find the cell containing the supplied string
Sub Find_String(sFindText As String)
Dim i As Integer

' Integer used in 'For' loop

Dim iRowNumber As Integer ' Integer to store result in


iRowNumber = 0

' Loop through cells A1-A100 until 'sFindText' is found


For i = 1 To 100
If Cells(i, 1).Value = sFindText Then
' A match has been found to the supplied string
' Store the current row number and exit the 'For' Loop
iRowNumber = i
Exit For
End If
Next i
' Pop up a message box to let the user know if the text
' string has been found, and if so, which row it appears on
If iRowNumber = 0 Then
MsgBox "String " & sFindText & " not found"
Else
MsgBox "String " & sFindText & " found in cell A" & iRowNumber
End If
End Sub

Don't worry if you don't understand some of the code in the example
above - this will be explained later in this tutorial. The example has
been included simply to show how comments are used to explain
each section of the code.

It is easy to get lazy about adding comments to your code, but it


really is worth making the effort. The minutes invested in ensuring
your code is well documented could save you hours of frustration in
the long term.

Code Indentation

Another way of assisting in making your code readable is by adding


indentations to it. You can see how, in the example above, the code
has been indented within the main Sub procedure and then indented
further inside individual blocks of code. These indented sections
enable you to easily see where each block of code starts and ends.

Line Breaks

Your code can also be made more readable by inserting line breaks
in the middle of long lines of code. In VBA, if you want to split a line
up, you need to add a space followed by an underscore ( _) just
before the line break. This tells the VBA compiler that the current
line of code continues on the following line.
The following example shows how simple line breaks can be used to
make long lines of code much easier to read and understand.
Consider the following 'If' statement:
If (index = 1 And sColor1 = "red") Or (index = 2 And sColor1 =
"blue") Or (index
=
3 And sColor1
=
"green") Or (index
=
4 And sColor1 = "brown") Then

By adding line breaks the same 'If' statement can be presented as


follows:
If (index
(index
(index
(index

=
=
=
=

1
2
3
4

And
And
And
And

sColor1
sColor1
sColor1
sColor1

=
=
=
=

"red") Or _
"blue") Or _
"green") Or _
"brown") Then

When the 'If' statement is broken up over four lines, you can see the
different conditions within the 'If' statement much more clearly. This
example illustrates how presenting your code in a clear way can
help you to produce readable code, which will help you to avoid
introducing bugs or errors.

Excel VBA Tutorial Part 2 - VBA Variables &


Constants
In VBA, as in any programming language Variables and Constants
are names that represent values. As suggested by the names, the
values of Variables can change, while Constants generally have fixed
values.
For example, you might use the constant "Pi" to store the value
3.14159265... The value of "Pi" will not change throughout the
course of your program, but it is useful to store this value in a
Constant for ease of use.
Also, we might use a variable named "sVAT_Rate", to store the VAT
Rate to be paid on purchased goods. The value of sVAT_Rate may
vary, depending on the type of goods.

Data Types

All variables and constants have a data type. The following table
shows the VBA data types, along with a description of each type and
the range of possible values.
Data Type

Byte

Boolean

Integer

Long

Single

Double

Currency

Date

Object

String

Variant

From the above table, it is clear that you can save on memory by
using specific data types (e.g. Integers rather than Longs, or Singles
rather than Doubles). However, if you are planning to use the
'smaller' data types, you must be sure that your code will not
encounter larger values than can be handled by the data type.

Declaring Variables & Constants

Before using a variable or constant, you can declare it. This is done
by adding a simple line of code to your macro, as follows.
To declare a variable:
Dim Variable_Name As Data_Type
Note that in the above line of code, Variable_Name should be
replaced by your actual variable name and Data_Type should be
replaced by one of the above listed data types. For example:

Dim sVAT_Rate As

Single

Dim i As Integer
Constants are declared in a similar way, except a constant should
always be assigned a value when it is declared. Examples of the
declaration of constants in VBA are:
Const iMaxCount

5000

Const iMaxScore = 100


Reasons to Declare Variables

Excel does not force you to declare variables. By default, all


variables in Excel will have the Variant type, and can be assigned a
number or text.
Therefore, at any point during your program, you can use any
variable name (even if it has not been declared), and Excel will
assign the Variant type to it. However, this is not good programming
practice for the following reasons:

1.

Memory & Calculation Speed: If you do not declare a


variable to have a data type, it will, by default, have the Variant
type. This takes up more memory than many of the other data
types.
While a few extra bytes per variable might not seem to be a lot of
memory, it is not uncommon for programmers to have thousands
of variables in their programs (especially when you start to use
arrays). Therefore, the additional memory used to store Variants
instead of Integers or Singles, can add up significantly.
Variant data types also take more time to process than some of

the other data types, so if you have thousands of unnecessary


Variant data types, this can slow down your calculations.
2.

Prevention of 'Typo' Bugs: If you always declare your


variables, then you can use the VBA Option Explicit (see below)
to force you to declare variables.
This will prevent you from introducing bugs into your code by
accidentally typing a variable name incorrectly. For example, you
might be using a variable called "sVAT_Rate" and, when assigning
a value to this variable, you might accidentally type "VATRate =
0.175". From this point onwards, you are expecting your variable
"sVAT_Rate" to have the value 0.175, but of course it doesn't.
However, if you were using the VBA option to force you to declare
all variables before using them, this error would be highlighted by
the VBA compiler, as the variable "VATRate" would not have been
declared.

3.

Highlighting Unexpected Data Values: If you declare a


variable to have a specific data type, and you attempt to assign
the wrong type of data to it, this will generate an error in your
program which, if not handled within your code, can cause your
programme to crash.
While this may initially seem to be a good reason not to declare
variables, it is actually useful to know as soon as possible if your
variable receives an unexpected data type. Otherwise, if the
program continues to run, you could end up with incorrect or
unexpected results at a later time, when it is likely to be much
more difficult to detect the causes of the errors.
Also, it is possible that the macro may complete with incorrect
results, and you may not notice the error at all- and continue to
work with incorrect data!

It is therefore preferable to detect the unexpected data type at an


early stage and add code to handle this appropriately.
Therefore, it is recommended that you always declare all variables
when programming in VBA, and use the Option Explicit (see below)
to ensure that all variables in the code are declared.

Option Explicit

The option 'Explicit' forces you to declare all variables that you use
in your VBA code, by highlighting any undeclared variables as errors
during compilation (before the code will run). To use this option,
simply type the line
Option Explicit
at the very top of your VBA file.
If you want to always include the option Explicit at the top of every
new VBA module that you open up, this can be done automatically
via the 'Require Variable Declaration' option of your VBA editor.
To do this:

In the Visual Basic Editor, select ToolsOptions...;


Ensure the Editor tab is selected;
Check the box next to the option Require Variable
Declaration and click OK.

Once the 'Require Variable Declaration' option is selected,


the Option Explicit will automatically be inserted at the top of all
new modules.

Scope of Variables and Constants

Each time you declare a variable or a constant, this only has a


limited Scope (i.e. a limited part of the program over which the
variable exists). This depends on the position of your declaration.
For example, imagine you are using the variable "sVAT_Rate" within
the function, "Total_Cost". The following table discusses the scope of
"sVAT_Rate" when it is declared in 2 different places within the
module:

Option Explicit
Dim sVAT_Rate As

If you declare "sVAT_Rate", at the top of your

Single

module file, then the scope of this variable is the


whole of the module (i.e. "sVAT_Rate" will be

Function Total_Cost() As

recognised throughout all procedures within the

Double

module).

.
.
.
End Function

Therefore, if you assign a value to "sVAT_Rate" in


the

Total_Cost function

and

then step

into

another function in the current module, the


assigned

value

of

"sVAT_Rate"

will

be

remembered.
However, if you step into a function that resides
in a different module and attempt to use the
variable "sVAT_Rate", the variable will not be
recognised.

Option Explicit

If you declare "sVAT_Rate", at the start of the


Function Total_Cost() As

Total_Cost function, the scope of this variable will

Double

be the whole of this function, (i.e. "sVAT_Rate"

Dim sVAT_Rate As
Single
.
.
.
End Function

will be recognised throughout the Total_Cost


function, but not outside of this function).
Therefore, if you attempt to use "sVAT_Rate" in
any other procedure, the VBA compiler will raise
an error, as the variable has not been declared
outside of the Total_Cost function (and the Option
Explicit is in use).

In the above example, the module level variable has been declared
using the 'Dim' keyword. However, it is possible that you may want
to declare variables that can be shared with other modules. This can
be specified by using the keyword Public in the declaration, instead
of 'Dim'.
Note that, for a module-level variable, the 'Dim' keyword could also
be replaced with the keyword Private to indicate that the scope of
the variable is limited to the current module.
Constants can also use the 'Public' and 'Private' keywords, but in this
case, the 'Public' or 'Private' keyword is used in addition to the
'Const' keyword (not instead of).
The following examples show the Public and Private keywords
applied to variables and constants:

Option Explicit
Public sVAT_Rate As

This example shows the 'Public' keyword used to

Single

declare

Public Const iMax_Count

constant, "iMax_Count". The scope of these two

= 5000

declarations is the whole of the current project.

Therefore "sVAT_Rate" and "iMax_Count" can be

accessed from any procedure in any module in

the project.

the

variable,

"sVAT_Rate",

and

the

Option Explicit
Private sVAT_Rate As

This example shows the 'Private' keyword used

Single

to declare the variable, "sVAT_Rate", and the

Private

constant, "iMax_Count". The scope of these two

Const iMax_Count =

declarations is the current module.

5000

Therefore "sVAT_Rate" and "iMax_Count" can be

accessed from any procedure in the current

module,

procedures that reside in different modules.

but

can

not

be

accessed

from

Excel VBA Tutorial Part 3 - Excel Visual Basic


Arrays
Excel Visual Basic arrays are structures which are used to store a set
of related variables of the same type. Each of the entries in the
array can be accessed by an index number.

For example, if you had 20 members of a team and you wanted to


store all the names for use in your VBA code. You could declare 20
variables to hold the team member names, as follows:
Dim Team_Member1 As String
Dim Team_Member2 As String
.
.
.
Dim Team_Member20 As String

Alternatively, you could use the much simpler and more organised
method of storing the Team members in an array of 20 String
variables:
Dim Team_Members(1 To 20) As String

Once you have declared the array as above, each entry of the array
is populated as follows:
Team_Members(1) = "John Smith"
.
.
.

A further advantage of storing your data in an array, rather than in


individual variables, arises if you want to perform the same action
on every member of the list. If your team member names were

stored in 20 individual variables, you would need 20 lines of code to


carry out a specific action on each name. However, if you have
stored your names in an array, you can use a simple loop to carry
out the action for each entry in the array.
This is shown in the example code below, which prints out each
name in the Team_Members array to a cell in Column A of the
current Excel Worksheet:
For i = 1 To 20
Cells(i, 1).Value = Team_Members(i)
Next i

It is clear from the above that handling an array of 20 names is


much less cumbersome and more organised than handling 20
individual variables, but imagine if you had 1,000 names to store!
And imagine you wanted to store Surnames separately from
Forenames! It is clear that it would soon become almost impossible
to handle this amount of data without the use of Arrays in your VBA
code.

Multi-Dimensional Excel Visual Basic Arrays

The Visual Basic Arrays discussed above are one-dimensional, in


that they refer to one list of Names. However, arrays can have
multiple dimensions. An array having two dimensions acts as a grid
of values.
For example, imagine that you want to store daily sales figures for
the month of January, for 5 different teams. You would need a 2-

dimensional array, consisting of 5 sets of figures over 31 days. You


would then declare the array as follows:
Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency

In order to access the entries in the array 'Jan_Sales_Figures', you


need to use two indices, refering to the day of the month and the
team number. For example, the sales figures for Team2 on January
15th would be referenced as:
Jan_Sales_Figures(15, 2)

You can declare arrays with 3 or more dimensions in the same way i.e. by adding further dimensions into the declaration and using a
further index to reference the array entries.

Declaring Excel Visual Basic Arrays

The above sections have already given some examples of Visual


Basic Array declarations, but it is worth discussing this further. As
seen above, a one-dimensional array can be declared as follows:
Dim Team_Members(1 To 20) As String

This declaration tells the VBA compiler that the array


'Team_Members' has 20 variables, which are referenced by indices 1

to 20. However, we could also decide to number our array variables


from 0 to 19, in which case the declaration would be:
Dim Team_Members(0 To 19) As String

In fact, the default form of array indexing is to start at 0, so if you


omit the start index from the declaration, and simply declare the
array as:
Dim Team_Members(19) As String

Then the VBA compiler will understand this to be an array of 20


variables, which are indexed from 0 to 19.
The same rules are applied to declarations of multi-dimensional
Visual Basic arrays. As shown in the previous example, a twodimensional array is declared by separating the dimension indices
by a comma:
Dim Jan_Sales_Figures(1 To 31, 1 To 5) As Currency

However, if we omit the start indices from both dimensions, as


follows:
Dim Jan_Sales_Figures(31, 5) As Currency

this is understood to be a two-dimensional array in which the first


dimension has 32 entries, indexed from 0 to 31 and the second
dimension has 6 entries, indexed from 0 to 5.

Dynamic Arrays

In the above examples, the arrays all have fixed dimensions.


However, in many cases, we don't know how big an array is going to
be before run time. We could solve this be declaring a huge array, in
an attempt to cover the maximum possible size needed, but this
would use up an unnecessarily large amount of memory and could
slow down your program. A better option would be to use
a Dynamic array, which is an array that can be sized and re-sized as
many times as you like, during the execution of a macro.
A dynamic array is declared with empty parentheses, as follows:
Dim Team_Members() As String

You then need to declare the dimension of the array during the
execution of the code, using the ReDim statement:
ReDim Team_Members(1 To 20)

If, during the execution of the code, you need to extend the size of
your array, you can useReDim again:
If Team_Size > 20 Then

ReDim Team_Members(1 To Team_Size)


End If

It should be noted that resizing a dynamic array in this way will


result in the loss of all the values that had previously been stored in
the array. If you want to avoid this loss, and keep the values that
have previously been assigned to the array, you need to use the
"Preserve" keyword, as shown below:
If Team_Size > 20 Then
ReDim Preserve Team_Members(1 To Team_Size)
End If

The disadvantage of using the "Preserve" keyword when resizing


Visual Basic Arrays is that you can only change the upper bound of
an array, not the lower bound. Also, if you have a multi-dimensional
array, the use of the "Preserve" keyword limits you to changing only
the last dimension of the array.

Excel VBA Tutorial Part 4 - VBA Function & Sub


Procedures
User-Defined VBA Function & Sub Procedures

In Excel Visual Basic, a set of commands to perform a specific task is


placed into a procedure, which can be a Functionprocedure or
a Sub procedure (also known as functions and subroutines).

The main difference between a VBA Function procedure and a Sub


procedure is that a Function procedure returns a result, whereas a
Sub procedure does not.
Therefore, if you wish to perform a task that returns a result (e.g.
summing of a group of numbers), you will generally use a Function
procedure, but if you just need a set of actions to be carried out (e.g.
formatting a set of cells), you might choose to use a Sub procedure.

Arguments

VBA procedures can be passed data viaarguments, which are


declared in the procedure definition. For example, you might have a
VBA Sub procedure that adds an Integer to every cell in the current
range. You could supply the value of the integer to the Sub via an
argument, as follows:

Sub AddToCells(i As Integer)


.
.
.
End Sub

Note that it is not essential for VBA Functions or Subs to have


arguments. Some procedures may not require them.

Optional Arguments

You can also define VBA procedures to have Optional arguments.


These are arguments that the user can supply if they want, but if
they are omitted, the procedure will assign a default value to them.
To return to the example above, if we wanted to make the supplied
integer argument optional, this would be declared as follows:
Sub AddToCells(Optional i As Integer = 0)

In this case, the supplied integer, i, has a default value of 0.


You can use multiple Optional arguments in a VBA procedure, as
long the Optional arguments are all positioned at the end of the
argument list.

Passing Arguments By Value and By Reference

When arguments are passed to VBA procedures, they can be passed


in two ways:

ByVal - The argument is passed by Value. This means that just


the value (i.e. a copy of the argument) is passed to the procedure
and therefore, any changes that are made to the argument inside
the procedure will be lost when the procedure is exited.

ByRef - The argument is passed by Reference. This means that


the address of the argument is passed to the procedure. Any
changes that are made to the argument inside the procedure will
be remembered when the procedure is exited.

You can specify whether an argument is passed to a VBA procedure


by value or by reference by using the ByVal or the ByRef keyword
when defining the procedure. This is shown below:

Sub AddToCells(ByVa

In this case, the integer i is passed by Value. Any

l i As Integer)

changes that are made to i will be lost when you exit

the Sub procedure.

.
.
End Sub

Sub AddToCells(ByRe

In this case, the integer i is passed by Reference.

f i As Integer)

When you exit the Sub, any changes that have been

made to i will be remembered by the variable that

was passed into the Sub procedure.

.
End Sub

It should be noted that by default, in VBA, arguments are passed by


Reference.
Therefore,
if
you
do
not
use
the ByVal or
the ByRef keyword, the arguments will be passed by Reference.
Before discussing further properties of VBA Function and Sub
procedures, it is useful to look at the two types of procedure
individually. The following two sections provide a brief discussion of
VBA Function and VBA Sub procedures, along with simple examples.

VBA Function Procedures

The VBA editor recognises a Function procedure, because the


commands are positioned between the following start and end
commands:

Function
.
.
.
End Function

As previously mentioned, VBA function procedures (unlike sub


procedures) return a value. The return values have the following
rules:

The data type of the returned value must be declared in the


Function header.

The value to be returned must be assigned to a variable having


the same name as the Function. This variable does not need to be
declared, as it already exists as a part of the function.

This is illustrated in the following example.

VBA Function Procedure Example: Perform a Mathematical Operation on 3


Numbers

The following code shows an example of a simple VBA Function


procedure that receives three arguments, each of which are
'Doubles' (double precision floating point numbers). The Function
returns a further 'Double', which is the sum of the first two
arguments, minus the third argument:

Function SumMinus(dNum1 As Double, dNum2 As Double, dNum3 As Double) As


Double
SumMinus = dNum1 + dNum2 - dNum3
End Function

The above very simple VBA Function procedure illustrates the way in
which data arguments are supplied to a procedure. It is also seen
that the Function procedure return type is defined as being a
'Double' (i.e. by the term "As Double" which is included after the
Function arguments).
The above example also shows how the Function procedure result is
stored in a variable that has the same name as the Function.

Calling VBA Function Procedures

If the above simple Function procedure is typed into a Module in the


Visual Basic Editor, it will then be available to be called from other
VBA procedures or to be used in the worksheets of your Excel
workbook.
Calling a VBA Function Procedure From Another Procedure

You can call a Function procedure from within another VBA


procedure by simply assigning the Function to a variable. The
following example shows a call to the simple SumMinus function that
was defined above:

Sub main()
Dim total as Double
total = SumMinus(5, 4, 3)
End Sub

Calling a VBA Function Procedure From A Worksheet

You can call VBA Function procedures from an Excel Worksheet, in


the same way as you can call any of the built-in Excel functions.
Therefore, you could call the SumMinus Function procedure by
typing the following into any cell of your worksheet:
=SumMinus(10, 5, 2)

VBA Sub Procedures

The VBA editor recognises a Sub procedure, because the commands


are positioned between the following start and end commands:

Sub

.
.
.
End Sub

VBA Sub Procedure Example 1: Center and Apply Font Size to a Selected
Range of Cells

The following code shows an example of a simple VBA Sub


procedure that applies formatting to the current selected cell range.
The cells are formatted to be aligned centrally (both horizontally and
vertically) and to have a user-supplied font size:

Sub Format_Centered_And_Sized(Optional iFontSize As Integer = 10)


Selection.HorizontalAlignment = xlCenter
Selection.VerticalAlignment = xlCenter
Selection.Font.Size = iFontSize
End Sub

The above example illustrates how Sub procedures perform actions


but do not return values.
This example also includes the Optional argument, iFontSize. If
iFontSize is not supplied to the Sub, then the default font size of 10

is used. However, if iFontSize is supplied to the Sub, then the current


range is set to have the user-supplied font size.

VBA Sub Procedure Example 2: Center and Apply Bold Font to a Selected
Range of Cells

The following code is similar to example 1, but instead of supplying


a font size to the selected range, the cells are set to have a bold
font. This example has been included to show a Sub procedure that
does not receive any arguments :

Sub Format_Centered_And_Bold()
Selection.HorizontalAlignment = xlCenter
Selection.VerticalAlignment = xlCenter
Selection.Font.Bold = True
End Sub

Calling Excel VBA Sub Procedures


Calling a VBA Sub Procedure From Another Procedure

You can call a VBA Sub procedure from another VBA procedure by
typing the Call keyword, followed by the Sub name and then the Sub
procedure arguments enclosed in brackets. This is shown in the
example below:

Sub main()
Call Format_Centered_And_Sized( 20 )
End Sub

If the Format_Centered_And_Sized Sub procedure had more than


one argument, these would be separated by commas. E.g.

Sub main()
Call Format_Centered_And_Sized( arg1, arg2, ... )
End Sub

Calling a VBA Sub Procedure From A Worksheet

Sub procedures cannot be typed directly into a Worksheet in Excel,


in the same way that VBA Function procedures can, because Sub
procedures don't return a value. However, provided they have no
arguments (and are Public - see below), Excel VBA Sub
procedures are available to the user of a spreadsheet. Therefore, if
the above simple Sub procedures are typed into a Module in the
Visual Basic Editor, the Format_Centered_And_Bold Sub procedure
will be available to be used in the worksheets of your Excel
workbook but the Format_Centered_And_Sized will not (as it has an
argument).

For those Sub procedures that are accessible from the workbook, a
simple way to run (or execute) the Sub is:

Press ALT-F8 (i.e. press the ALT key and while this is pressed
down, press F8);

The Macro dialog box, containing a list of available macros will


appear;

From the list of macros select the macro you wish to run and
click the Run button.

Assigning a Keyboard Shortcut to a Sub Procedure

You can assign a key combination to your Sub procedure, to enable


quick and easy execution of the code. To do this:

Press ALT-F8 (i.e. press the ALT key and while this is pressed
down, press F8);

From the list of macros in the Macro dialog box, select the
macro you wish to assign a key combination to;

Click Options... to open the 'Macro Options' dialog box;


Type the required keyboard shortcut into the 'Macro Options'
dialog box;

Click OK and then shut down the 'Macro' dialog box.

WARNING: When assigning a key combination to a macro, take care


not to select one of Excel's predefined key combinations (eg. CTRLC). If you do select an existing Excel key combination, this will be
overwritten by your macro, and you, or other users, may end up
accidentally executing your macro code.

Scope of VBA Procedures

In Part 2 of this tutorial, we discussed the scope of variables and


constants and the role of thePublic and Private keywords. These
keywords have the same meaning when applied to VBA procedures :

Public

If a procedure declaration is preceded by the

Sub AddToCells(i

keyword Public, this makes the procedure accessible to

As Integer)

all other modules in the VBA Project.

.
.
.
End Sub

Private

If a procedure declaration is preceded by the

Sub AddToCells(i

keyword Private, this makes the procedure only available

As Integer)

to the current module. It cannot be accessed from any

other modules, or from the Excel workbook.

.
.
End Sub

If no keyword is inserted at the start of a VBA Function or Sub


declaration, then the default setting is for the procedure to
be Public (i.e. to be accessible from anywhere in the VBA Project).
This is different to variable declarations, which are Private by
default.

Early Exit From VBA Function & Sub Procedures

If you want to exit a VBA Function or Sub procedure before it has run
to the end, you can do this using the Exit Function or the Exit
Sub command. This is illustrated below, in a simple Function
procedure that expects to receive a positive value to work with. If
the value received is not positive, the function cannot continue, so it
highlights the error to the user and exits the procedure immediately:

Function VAT_Amount(sVAT_Rate As Single) As Single


VAT_Amount = 0
If sVAT_Rate <= 0 Then
MsgBox "Expected a Positive value of sVAT_Rate but Received " & sVAT_Rate
Exit Function
End If
.
.
.
End Function

Note that, before exiting the VAT_Amount Function procedure, the


above code uses the built-in VBA MsgBox function, to display a box
containing a warning message to the user.

Excel VBA Tutorial Part 5: VBA Conditional


Statements
The main Excel VBA Conditional Statements are
Thenstatement and the Select Casestatement. Both

the If ...
of these

evaluate one or more conditions and, depending on the result,


execute specific actions.
The two Conditional Statement types are discussed individually
below.

The Visual Basic If ... ThenStatement

The If ... Then statement tests a condition and if it evaluates to True,


carries out a set of actions. If the condition evaluates to False, a
different set of actions are carried out.
The format of the If ... Then statement is:

If Condition1 Then
Actions if Condition1 evaluates to True
ElseIf Condition2 Then
Actions if Condition2 evaluates to True
Else
Actions if none of the previous conditions evaluate to True
End If

In the above If statement, the ElseIf and the Else parts of the
conditional statement can be left out if desired.

In the example below, an If ... Then statement is used to color the


current active cell, depending on the value of the cell contents.

If ActiveCell.Value < 5 Then


ActiveCell.Interior.Color = 65280 ' Color cell interior green
ElseIf ActiveCell.Value < 10 Then
ActiveCell.Interior.Color = 49407 ' Color cell interior orange
Else
ActiveCell.Interior.Color = 255

' Color cell interior red

End If

Note that, in the above example, the conditional statement stops


once it has satisfied a condition. Therefore, if the ActiveCell value is
less than 5, the first condition is satisfies and so the cell is colored
green. The If ... Then statement is then exited, without testing any
further conditions.

Further information on the VBA If ... Then statement is provided on


the Microsoft Developer Network website.

The Visual Basic Select Case Statement

The Select Case statement is similar to the If ... Then statement, in


that it tests an expression, and carries out different actions,
depending on the value of the expression.
The format of the Select Case statement is:

Select Case Expression


Case Value1
Actions if Expression matches Value1
Case Value2
Actions if Expression matches Value2
.
.
.
Case Else
Actions if expression does not match any of listed cases
End Select

In the above code block, the Case Else part of the conditional
statement is optional.
In the example below, the Select Case statement is used to color the
current active cell, depending on the value of the cell contents.

Select Case ActiveCell.Value


Case Is <= 5
ActiveCell.Interior.Color = 65280 ' Color cell interior green
Case 6, 7, 8, 9
ActiveCell.Interior.Color = 49407 ' Color cell interior orange
Case 10
ActiveCell.Interior.Color = 65535 ' Color cell interior yellow
Case Else
ActiveCell.Interior.Color = 255

' Color cell interior red

End Select

The above example illustrates different ways of defining the


different Cases in the Select Casestatement. These are:
Case
Is <= 5

This is an example of how you can test if your


expression satisfies a condition such as <= 5 by
using the keyword Case Is

Case 6, 7,
8, 9

This is an example of how you can test if your


expression evaluates to any one of several
values, by separating the possible values by
commas

Case 10

This is an example of the basic test of whether


your expression evaluates to a specific value

Case Else

This is an example of the 'Else' condition, which


is executed if your expression hasn't matched
any of the previous cases

Note that as soon as one case in the Select Case statement is


matched, and the corresponding actions executed, the whole Select
Case statement is exited. Therefore, you will never get entry into
more than one of the listed cases.

Excel VBA Tutorial Part 6 - VBA Loops


If, in your VBA program, you need to perform the same task (i.e.
repeat the same piece of code) multiple times, this can be done
using one of the VBA Loops.
The VBA Loop types are:
The For Loop
The Do While Loop
The Do Until Loop

Each of the above loop types is discussed separately below.

The Visual Basic For Loop

The Visual Basic 'For' loop takes on two separate forms. These are
the For ... Next loop and the For Each loop.
The For ... Next Loop

The For ... Next loop uses a variable, which is set to a series of
values within a specified range. The VBA code inside the loop is then
executed for each value. This is best explained by way of a simple
example:

For i = 1 To 10
Total = Total + iArray(i)
Next i

The above simple For ... Next loop sets the variable i to have the
values 1, 2, 3, ..., 10, and for each of these values, runs through the
VBA code inside the loop. Therefore, in the above example, the loop
adds each of the members of the array 'iArray' to the variable,
'Total'.
In the above example, no step size is specified, so the loop uses the
default step size of 1, when looping from 1 to 10. However, you may
sometimes want to step through a loop using different sized steps.
This can be done using the Step keyword, as shown in the following
simple example.

For d = 0 To 10 Step 0.1


dTotal = dTotal + d

Next d

In the above For loop, because the step size is specified as 0.1, the
value of the variable d is set to the values 0.0, 0.1, 0.2, 0.3, ..., 9.9,
10.0 for each execution of the VBA code inside the loop.
You can also use negative step sizes in the VBA For loop, as is
illustrated below:

For i = 10 To 1 Step -1
iArray(i) = i
Next i

In this example, the step size is specified as -1, and so the loop sets
the variable, i, to have the values, 10, 9, 8, ..., 1.

The For Each Loop

The For Each loop is similar to the For ... Next loop but, instead of
running through a set of values for a variable, the For Each loop runs
through every object within a set of objects. For example, the
following code shows the For Each loop used to list every Worksheet
in the current Excel Workbook:

Dim wSheet As Worksheet


For Each wSheet in Worksheets
MsgBox "Found Worksheet: " & wSheet.Name
Next wSheet

The Exit For Statement

If, you want to exit a 'For' Loop early, you can use the Exit
For statement. This statement causes VBA to jump out of the loop
and continue with the next line of code outside of the loop. For
example, you may be searching for a particular value in an array.
You could do this by looping through each entry of the array, but
when you find the value you are looking for, you no longer wish to
continue searching, so you exit the loop early.
The Exit For statement is illustrated in the following example, which
loops through 100 array entries, comparing each to the value 'dVal'.
The loop is exited early if dVal is found in the array:

For i = 1 To 100
If dValues(i) = dVal Then
indexVal = i
Exit For
End If
Next i

The Visual Basic Do While Loop

The Do While loop repeatedly executes a section of code while a


specified condition continues to evaluate to True. This is shown in
the following Sub procedure, where a Do While loop is used to print
out all values of the Fibonacci Sequence until the values exceed
1,000:

' Sub procedure to list the Fibonacci series for all values below 1,000
Sub Fibonacci()
Dim i As Integer ' counter for the position in the series
Dim iFib As Integer ' stores the current value in the series
Dim iFib_Next As Integer ' stores the next value in the series
Dim iStep As Integer ' stores the next step size
' Initialise the variables i and iFib_Next
i=1
iFib_Next = 0
' Do While loop to be executed as long as the value of the
' current Fibonacci number exceeds 1000
Do While iFib_Next < 1000
If i = 1 Then
' Special case for the first entry of the series
iStep = 1
iFib = 0
Else
' Store the next step size, before overwriting the

' current entry of the series


iStep = iFib
iFib = iFib_Next
End If
' Print the current Fibonacci value to column A of the
' current Worksheet
Cells(i, 1).Value = iFib
' Calculate the next value in the series and increment
' the position marker by 1
iFib_Next = iFib + iStep
i=i+1
Loop
End Sub

It can be seen that, in the above example, the condition iFib_Next <
1000 is tested at the start of the loop. Therefore, if the first value of
iFib_Next were greater than 1,000, the loop would not be executed
at all.
Another way that you can implement the Do While loop is to place
the condition at the end of the loop instead of at the beginning. This
causes the loop to be executed at least once, regardless of whether
or not the condition initially evaluates to True.
The following code shows the form of a Do While Loop which has the
condition at the end of the loop:

Do
.
.
.
Loop While iFib_Next < 1000

The Visual Basic Do Until Loop

The Do Until loop is very similar to the Do While loop. The loop
repeatedly executes a section of code until a specified condition
evaluates to True. This is shown in the following sub procedure,
where a Do Until loop is used to extract the values from all cells in
Column A of a Worksheet, until it encounters an empty cell :

iRow = 1
Do Until IsEmpty(Cells(iRow, 1))
' Store the current cell value in the dCellValues array
dCellValues(iRow) = Cells(iRow, 1).Value
iRow = iRow + 1
Loop

In the above example, since the condition IsEmpty(Cells(iRow, 1)) is


at the start of the Do Untilloop, the loop will only be entered if the
first cell encountered is non-blank.
However, as illustrated in the Do While loop, you may on some
occasions want to enter the loop at least once, regardless of the
initial condition. In this case, the condition can be placed at the end
of the loop, as follows:

Do
.
.
.
Loop Until IsEmpty(Cells(iRow, 1))

Excel VBA Tutorial Part 7 - VBA Operators &


Built-In Functions
VBA includes several built-in operators and functions, which can be
used for building expressions and quickly performing basic tasks in
your VBA code.
Excel VBA Operators

The built-in VBA operators consist of mathematical operators, string


operators, comparison operators and logical operators. The different
types of Operators are discussed individually below.

Mathematical Operators

The main Mathematical VBA operators are listed in the table below.
The precedences that are listed alongside the operators are the
defaults, which are applied in the absence of brackets. However, the
order in which the VBA operators are applied can be controlled by
adding brackets to an expression:

Operator

^
*
/
\
Mod
+
-

String Operators

The concatenate operator & can be used to join together strings:

Operator
&

VBA Comparison Operators

Comparison operators compare two numbers or strings and return a


logical (True or False) result. The main Excel VBA comparison
operators are listed in the table below:

Oper

<

<

>

<

>

VBA Logical Operators

Logical operators also return a logical (True or False) result. The


main Excel VBA logical operators are listed in the table below:
Operator
And
Or
Not

It should be noted that the above tables are not an exhaustive list of
VBA operators. A more complete list can be obtained from the Visual
Basic Developer Center Website

Built-In Functions

VBA also has a large number of built-in functions that are available
to be used in your VBA code. Some of the more commonly used VBA
functions are listed below.
Functio
n

Action

Abs

Returns the absolute value of a supplied number.


e.g.

Abs(-20) returns the value 20;

Abs(20) returns the value 20.

Chr

Returns the character associated with a supplied


character code.
e.g.

Chr(97) returns the character "a".

Chr(10) returns a line feed;

Date
DateAd
d

Returns the current system date.

Adds a specified time period to a supplied date.


The function has
Number, Date),

the

format DateAdd(Interval,

where the Interval argument specifies the type of


time interval to be added to the supplied date.
This can takes on one of the following values:
Interval

Represents

yyyy

year

quarter

e.g.

month

day of the year

day

weekday

ww

week

hour

minute

second

DateAdd("d", 32, "01/01/2015") adds 32 days to the


date "01/01/2015" and so returns the date
"02/02/2015".

DateAdd("ww", 8, "01/01/2015") adds 88 weeks to


the date "01/01/2015" and so returns the date
"09/09/2015".

DateDi
f

Calculates the number of specified intervals between


now and a supplied date
e.g.

DateDif("d", "01/01/2015", "02/02/2015")calculates


the number of days between the dates "01/01/2015"

and "02/02/2015", and so returns the value 32.

DateDif("w", "01/01/2015",
"03/03/2016")calculates the number of weeks between
the dates "01/01/2015" and "03/03/2016", and so
returns the value 61.

Day

Returns the day of the month for a supplied date


e.g.

Hour

Returns the Hour portion of a supplied time


e.g.

InStr

Day("01/29/2015") returns the value 29.

Hour("22:45:00") returns the value 22.

If supplied with an integer, n, and 2 strings, the InStr


function returns the position of the second string
within the first string, starting the search from the
n'th position in the first string.
E.g.

InStr(1, "Here is the searchword",


"searchword") returns the value 13.

InStr(14, "Here is the searchword but here is


another searchword", "searchword") returns the
value 44.

Int

Returns the integer part of a numeric value.


e.g.

IsDate

Int(5.79) returns the value 5.

Returns True if a supplied value is a date, and False


otherwise.
e.g.

IsDate("01/01/2015") returns the valueTrue;

IsDate(100) returns the value False.

IsError

Returns True if a supplied value is an error, and False


otherwise.

IsMissi
ng

If supplied with the name of an optional argument to


a function, the IsMissing function returns True if no
argument value was passed to the function.

IsNum
eric

Returns True if a supplied value can be evaluated as a


number, or False otherwise.

Left

Returns a specified number of characters from the


start of a supplied string.
The format of the function is Left(String, Length),
where String is the original text string and Length is
the number of characters to be returned from the

start of the supplied String.


E.g.

Left("abcdefghijklm", 4) returns the string "abcd";

Left("abcdefghijklm", 1) returns the string "a".

Len

Returns the length of a supplied text string.


E.g.

Month

Returns the month number for a supplied date.


e.g.

Mid

Len("abcdefg") returns the value 7.

Month("01/29/2015") returns the value 1.

Returns a specified number of characters from the


middle of a supplied string.
The format of the function is Mid(String, Start,
Length),
where String is the original text string, Start is the
start position of the section of String that is to be
returned and Length is the length of the returned
string.
E.g.

Mid("abcdefghijklm", 4, 5) returns the string


"defgh";

E.g.

Sqr(4) returns the value 2;

Sqr(16) returns the value 4.

Time
UBoun
d
Year

Returns the current system time.


Returns the upper subscript of a supplied array.

Returns the year of a supplied date.


E.g.

Year("01/29/2015") returns the value 2015

Excel VBA Tutorial Part 8 - Excel Objects


The term Excel Objects(collectively referred to as the Excel
Object Model) refers to the entities that make up an Excel
workbook, such as Worksheets, Rows, Columns, Cell Ranges, and the
Excel Workbook itself. Each object in Excel has a number
ofProperties, which are stored as a part of that object.
For example, an Excel Worksheet's properties include the
Worksheet's Name, Protection, Visible Property, Scroll Area, etc.
Therefore, if during the execution of a macro, we wanted to hide an
Excel worksheet, we could do this by accessing the Worksheet
object, and altering the 'Visible' property.
Excel VBA has a special type of object, called a Collection. As the
name suggests, a Collection refers to a group (or collection) of Excel

objects. For example, the Rows collection is an object containing all


the rows of a Worksheet.
The main Excel Objects can all be accessed (directly or indirectly)
from the Workbooks object, which is a collection of all the currently
open Workbooks. Each Workbook object contains the Sheets object
(consisting of all the Worksheets and Chart sheets in the Workbook),
and in turn, each Worksheet object contains a Rows object
(consisting of all Rows in the Worksheet) and a Columns object
(consisting of all Columns in the Worksheet), etc.
The following table lists some of the more commonly used Excel
objects. For a more comprehensive list of Excel VBA objects, see
the Microsoft Office Developer website.
Object
Type

Description

Applicati
on

The current Excel Application.

Workboo
ks

The Workbooks object is a collection of all of the


open Excel Workbooks in the current Excel
Application.
An individual Workbook can be extracted from
the Workbooks object by using an individual
Workbook index number or name (i.e.
Workbooks(1) or Workbooks("Book1")).

Workboo
k

A Workbook object can be accessed from the


Workbooks Collection by using a Workbook index

number or a Workbook name (e.g. Workbooks(1)


or Workbooks("Book1")). You can also use
'ActiveWorkbook' to access the current active
Workbook.
From the Workbook object, you can access the
Sheets object, which is a collection of all the
Sheets (Worksheets and Chart Sheets) in the
Workbook, and you can also access the
Worksheets object, which is a collection of all the
Worksheets in the Workbook.

Sheets

The Sheets object is a collection of all the Sheets


in a Workbook. These Sheets can be Worksheets
or Charts. An individual Sheet can be extracted
from the Sheets object by using an individual
Sheet index number or name (i.e. Sheets(1) or
Sheets("Sheet1")).

Workshe
ets

The WorkSheets object is a collection of all the


WorkSheets in a Workbook (i.e. all the Sheets,
except the Charts). An individual Worksheet can
be extracted from the Worksheets object by
using an individual Worksheet index number or
name (i.e. Worksheets(1) or
Worksheets("Wksheet1")).

Workshe
et

A Worksheet object can be accessed from the


Sheets or the Worksheets object by using a
Sheet or Worksheet index number or a Sheet or
Worksheet name (e.g. Sheets(1), Worksheets(1),

Sheets("Sheet1") or Worksheets("Wksheet1")).
You can also use 'ActiveSheet' to access the
current active Sheet.
From the Worksheet object, you can access the
Rows and Columns objects, which are collections
of Range objects relating to the Rows and
Columns of the Worksheet. You can also access
an individual cell or any Range of contiguous
cells on the Worksheet.

Rows

The Rows object is a collection of all the Rows of


a Worksheet. A Range object consisting of an
individual Worksheet row can be accessed by
using an index number (i.e. Rows(1))

Columns

The Columns object is a collection of all the


Columns of a Worksheet. A Range object
consisting of an individual Worksheet column can
be accessed by using an index number (i.e.
Columns(1))

Range

The Range object represents any number of


contiguous cells on a Worksheet. This can be just
one cell or it can be all the cells on the
Worksheet.
A range consisting of just one cell can be
returned from a Worksheet, using the Cells
property (i.e. Worksheet.Cells(1,1)).

Alternatively, a range can be referenced by


specifying either a cell range or a start and end
cell (e.g. Worksheet.Range("A1:B10") OR
Worksheet.Range("A1", "B10") OR
Worksheet.Range(Cells(1,1), Cells(10,2))).
Note that if the second cell reference is omitted
from the Range (e.g. Worksheet.Range("A1") OR
Worksheet.Range(Cells(1,1)), this will return a
range that consists of only one cell.

The above table describes how you access Excel objects via 'parent'
objects. For example, a range of cells may be referenced by the
expression:
Workbooks("WB1").Worksheets("WS1").Range("A1:B10")

Assigning an Object to a Variable

Another point to note, when working with Excel objects is that, when
an object is being assigned to a variable in your vba code, you must
use the Set keyword as follows:
Dim DataWb As Workbook
Set DataWb = Workbooks("Data.xlsx")

The Active Object

At any one time, Excel will have an Active Workbook, which is the
workbook that is currently selected. Similarly, there will be
an Active Worksheet and an Active Range, etc.
The current active Workbook or Sheet can be referred to, in your vba
code asActiveWorkbook, or ActiveSheet, and the current active
range can be accessed by referring toSelection.
If, in your VBA code, you refer to a worksheet, without referring to a
specific workbook, Excel defaults to the current Active Workbook.
Similarly, if you refer to a range, without referring to a specific
workbook or worksheet, Excel defaults to the current Active
Worksheet in the current Active Workbook.
Therefore, if you wish to refer to range A1:B10 on the current Active
Worksheet, within the current Active Workbook, you can simply type:
Range("A1:B10")
Changing the Current Active Object

If, during the execution of your code, you wish to change the current
Active Workbook, Worksheet, Range, etc, this can be done using the
'Activate' or 'Select' methods as follows:
Workbooks("Book1.xlsm").Activate
Worksheets("Data").Select
Range("A1", "B10").Select
Object Methods such as the 'Activate' and 'Select' methods used
above, are discussed in more detail below.

Object Properties

VBA objects have related properties associated to them. For


example, the Workbook object has the properties 'Name',
'RevisionNumber', 'Sheets', and many more. These properties can be
accessed by referring to the object name followed a dot and then
the property name. For example, the name of the current active
Workbook can be accessed by referring to ActiveWorkbook.Name.
Therefore, to assign the current active Workbook name to the
variable wbName, we could use the following code:
Dim wbName As String
wbName = ActiveWorkbook.Name
We previously illustrated how the Workbook object can be used to
access a Worksheet using the command
Workbooks("WB1").Worksheets("WS1")
This is because the Worksheets collection is a property of the
Workbook object.
Some object properties are read only, meaning that you cannot
change their values. However, some of the properties can have
values assigned to them. For example, if you wanted to change the
name of the current active sheet to "my worksheet", this could be
done by simply assigning the name "my worksheet" to the active
sheet's 'Name' property, as follows:
ActiveSheet.Name = "my worksheet"

Object Methods

VBA objects also have methods that perform specific actions. Object
methods are procedures that are associated to a specific object
type. For example, the Workbook object has the methods 'Activate',
'Close', 'Save', and many more.
An Object Method can be called by referring to the object name
followed a dot and then the method name. For example, the current
active Workbook can be saved using the code:
ActiveWorkbook.Save
Like any other procedures, methods can have arguments that are
supplied when the method is called. For example, the Workbook
'Close' method has three optional arguments which are used to
provide information to the method such whether the Workbook is to
be saved before closing, etc.
The method arguments are supplied to the method by following the
call to the method with the argument values, separated by commas.
For example, if you wanted to save the current active workbook as a
.csv file called "Book2", you would call the Workbook SaveAs
method with the Filename argument set to "Book2" and the
FileFormat argument set to xlCSV:
ActiveWorkbook.SaveAs "Book2", xlCSV
To make your code more readable, you can use named arguments
when calling a method. In this case, you type the argument name
followed by the assignment operator := and then the value.
Therefore, the above call to the Workbook SaveAs method could be
written as:
ActiveWorkbook.SaveAs Filename:="Book2", [FileFormat]:=xlCSV

A list of excel objects, with their properties and methods are


provided in the Object Browser within the Visual Basic Editor. To
display this, simply press F2 from within the Visual Basic Editor.

Examples
Example 1

The following VBA code snippet was previously used to illustrate the
use of the For Each loop. It is now useful to re-visit this code to
examine the references to the Worksheets object (taken from the
current active Workbook by default), and the reference to each
individual Worksheet. Note that the Worksheet Name property is
accessed, to display the name of each Worksheet.

' Cycle through each Worksheet in the current Workbook


' and display the Worksheet name in a message box
Dim wSheet As Worksheet
For Each wSheet in Worksheets
MsgBox "Found Worksheet: " & wSheet.Name
Next wSheet

Example 2

The following section of VBA code has been included to illustrate


how you can access Worksheets and Ranges from other Workbooks
and how the current Excel Objects are accessed by default if no
specific object is referenced. This example also illustrates the use of
the Set keyword to assign an Excel object to a variable.
The code also shows the PasteSpecial method being called for the
Range object. This method sets the 'Paste' argument to the value
'xlPasteValues'.

' Copy a range of cells from Sheet1 of another Workbook (named "Data.xlsx"),
' and paste the values into the "Results" Worksheet of the current Workbook
' (named "CurrWb.xlsm")
Dim dataWb As Workbook
Set DataWb = Workbooks.Open("C:\Data")
' Note that DataWb is the current Active Workbook.
' Therefore the following accesses the 'Sheets' Object in DataWb.
Sheets("Sheet1").Range("A1:B10").Copy
' Paste the values from the copied Range into the "Results" Worksheet of
' the current Workbook. Note that, as CurrWb is not the current Active
' Workbook, we need to specify this Workbook.
Workbooks("CurrWb").Sheets("Results").Range("A1").PasteSpecial
Paste:=xlPasteValues

Example 3

The following section of VBA code shows how the Columns


(collection) object can be accessed from the Worksheet object. It is

also seen that, when a cell or cell range on the current active
Worksheet is accessed, the reference to the Worksheet can be
omitted. Again the code provides an illustration of the use of
the Set keyword to assign a Range object to the variable 'Col'.
The code also includes an example of how to access and change the
Range object's Value property.

' Loop through the values in Column A of the Worksheet "Sheet2",


' perform arithmetic operations on each value, and write the result into
' Column A of the current Active Worksheet ("Sheet1")
Dim i As Integer
Dim Col As Range
Dim dVal As Double
' Set the variable 'Col' to be Column A of Sheet 2
Set Col = Sheets("Sheet2").Columns("A")
i=1
' Loop through each cell of the column 'Col' until
' a blank cell is encountered
Do Until IsEmpty(Col.Cells(i))
' Apply arithmetic operations to the value of the current cell
dVal = Col.Cells(i).Value * 3 - 1
' The command below copies the result into Column A
' of the current Active Worksheet - no need to specify
' the Worksheet name as it is the active Worksheet.
Cells(i, 1).Value = dVal
i=i+1

Loop

The term 'Excel Events' refers to specific actions that a user carries
out in Excel. For example, if the user selects a Worksheet, this is an
event. Similarly, entering data into a cell or saving a Workbook are
also Excel events.
Events are linked to Excel Worksheets, Charts, Workbooks, or to the
Excel Application itself. This enables the programmer to create vba
code to be executed automatically at the time of an event.
For example, if you wanted to run a macro every time a user
selected any Worksheet in the Workbook, this could be done by
writing vba code that is linked to the Workbook event
"SheetActivate".
Alternatively, if you wanted to run a macro every time
a specific Worksheet (e.g. "Sheet1") was selected, you would link
your code to the Worksheet event "Activate" for Sheet1.
How to Link Code to a Specific Event

1.

Open up the VBA Editor (by pressing ALT-F11) and open up the
code window for the object relating to the event that you are
interested in linking code to. For example, if you want to execute a
section of code every time a specific worksheet event occurs, you
should open up the code window for that worksheet. This is shown in
the image below:

2.

Click on the drop-down menu, at the top left of the code


window and select the object type (e.g. Worksheet). The dropdown
menu in the right window will then display the events that are
defined for that object. The image below shows the events that are
defined for an Excel Worksheet:

3.

Select an event from the top right drop-down menu. This


causes a Sub procedure to be automatically inserted into the code
window for that object. The arguments that Excel automatically

feeds into that function (if there are any) are included into the Sub
header - you then just need to add the vba code to define what you
want to do when that event is fired.

Example

The following example displays a message box every time the cell
B1 in the Worksheet "Sheet1" is selected.
For this action, we need to use the Worksheet Event
"Selection_Change", which 'fires' every time a different cell or range
of cells is selected. The "Selection_Change" function receives, as an
argument, a Range object called "Target". This tells you the range of
cells that has been selected.
As the "Selection_Change" event relates to any new selection, we
need to check the supplied Range, 'Target', as soon as the function
is called, to make sure that the required actions are performed, only
when cell B1 is selected. The code for this is shown below:

' Code to display a Message Box if Cell B1 of the current Worksheet


' is selected.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
' Check if the selection is cell B1
If Target.Count = 1 And Target.Row = 1 And Target.Column = 2 Then
' The selection IS cell B1, so carry out required actions
MsgBox "You have selected cell B1"
End If
End Sub

Excel VBA Tutorial Part 10 - VBA Error Types


VBA Error Types

There are three types of VBA error that you may encounter when
executing an Excel macro. These are:

Compile Errors;
Runtime Errors;
Logical Errors ('bugs').

These three VBA error types are discussed in turn, below.

Compile Errors

Auto Syntax Check Option


The Auto Syntax Check option causes a message box to pop up
whenever a syntax error is typed into the visual basic editor.
If this option is switched off, the visual basic editor still highlights
syntax errors in red.
The
Auto
Syntax
Check
option
is
accessed
by
selecting ToolsOptions from the menu at the top of the visual
basic editor.
Compile Errors are recognised by the VBA compiler as being illegal
and therefore, are highlighted as errors before your macro even
starts to run.
If you type in a syntax error, the VBA editor will immediately
highlight this, either by popping up a message box or by highlighting

the error in red, depending on the setting of the Auto Syntax Check
option (see right).
Alternatively, a compile error may be detected when the code is
compiled, just before being executed.

A compile error is generally easy to fix, as the VBA compiler pops up


a message box, which provides information on the nature of the
error.
For example, if you get the message "Compile error: Variable not
defined" when you attempt to run your code, this indicates that
you are attempting to use, or access, a variable that has not been
declared in the current scope. (This error is only generated when
you are using Option Explicit).

Runtime Errors

Runtime errors occur during the execution of your code, and cause
the code to stop running. This type of VBA error is also relatively
easy to fix, as you will be given details of the nature of the error,
and shown the location where the code has stopped running.
For example, if your code attempts to divide by zero, you will be
presented with a message box, which states"Run-time error '11':
Division by zero".
Depending on the structure of your VBA project, you may be given
the option to debug the code, (see below). In this case, clicking on
the Debug button on the debug message box, causes the line of
code that generated the VBA error to be highlighted in your vba
editor.

Due to the message box content and the highlighted line of code in
the above example, it is very easy to spot the error in this code.
If your code is more complex, you can gain further information on
the reason for the VBA error by looking at the values of the variables
in use. This can be done in the VBA editor by simply hovering your
mouse cursor over the variable name, or by opening the local
variables window (by selecting ViewLocals Window).

The different runtime error codes are explained on the Microsoft


Support Website. However, some of the more common VBA error
messages are shown in the table below:
5

Invalid procedure call

Out of memory

Subscript out of range


(this error arises if you attempt to
access elements of an array outside of
the defined array size - e.g. if you
define an array indexed from 1 to 10,
then attempt to access entry no. 11)

1
1

1
3

Division by zero

Type mismatch
(this error arises when you attempt to
assign the wrong type of value to a
variable - e.g. define i as an integer,
then attempt to assign the string "text"
to i)

5
3

File not found


(occurs when attempting to open a file)

Trapping Runtime Errors

Some runtime errors may not be caused by faulty code. For


example, if you need to open a file, that contains essential data for
your macro, you can't avoid the generation of a VBA error, if the file
does not exist. In these types of cases, it is far more professional to
'trap' the error, and write VBA code to handle it, so that your macro
exits gracefully, rather than having your macro crashing.
In order to assist with runtime error trapping, VBA provides us with
the On Error and theResume statements. These statements capture
a runtime error and divert the macro into a specified section of VBA
code, where the error is handled. After the error handling code has
run, the programmer can request that the VBA code resumes from
the point of the error, or alternatively, the macro can be terminated
cleanly. This is shown in the example code below.

' Sub procedure to set the supplied values, Val1 and Val2 to the values
' in cells A1 and B1 of the Workbook "Data.xls" in the C:\ directory
Sub Set_Values(Val1 As Double, Val2 As Double)
Dim DataWorkbook As Workbook
On Error GoTo ErrorHandling

' Open the Data Workbook


Set DataWorkbook = Workbooks.Open("C:\Documents and Settings\Data")
' Set the variables Val1 and Val2 from the data in DataWorkbook
Val1 = Sheets("Sheet1").Cells(1, 1)
Val2 = Sheets("Sheet1").Cells(1, 2)
DataWorkbook.Close
Exit Sub
ErrorHandling:
' If the file is not found, ask the user to place it into
' the correct directory and then resume
MsgBox "Data Workbook not found;" & _
"Please add the workbook to C:\Documents and Settings and click OK"
Resume
End Sub

In the code above, the code attempts to open the Excel File 'Data'
and if it fails to find the file, prompts the user to place the data file
into the correct folder. Once the user does this and clicks OK, the
code is resumed and a further attempt is made to open the file. If
desired, instead of re-trying the file, the Sub procedure could be
terminated at this point, by using theExit Sub command.

Logical Errors

Logical Errors, otherwise known as 'bugs', occur during the


execution of the VBA code, and allow the code to continue to run to
completion. However, the 'bug' may cause the macro to perform
unexpected actions or return an incorrect result. These errors are
the most difficult to detect and fix, as there is no way that the VBA
compiler can identify and 'point to' the error, in the way that it does
for compile and runtime errors.
For example, you may accidentally code your macro to add together
the wrong variables in a procedure. The result would be incorrect,
but the macro would usually continue to run to completion.
The Excel VBA editor provides a number of debugging tools to assist
you in finding logical errors in your VBA code, so that they can be
fixed. These tools are currently beyond the scope of this page.
However, an overview of the Excel VBA debugging tools is provided
on theMicrosoft Help & Support Website.