DICT06 Visual Basic For Applications (VBA) : Syllabus
DICT06 Visual Basic For Applications (VBA) : Syllabus
VBA performs actions faster, more accurately, more reliably, and far more cheaply than any human. As
long as you can define conditions for making a decision accurately, VBA can also make decisions for you.
By adding decision-making structures and loops (conditional repetitions) to your code, you can take it
far beyond the range of actions that the human user can perform.
Beyond automating actions, you would otherwise perform manually, VBA also gives you the tools to
create interfaces for your code — message boxes, input boxes, and user forms, graphical objects that
you can use to create forms and custom dialog boxes. You can manipulate the Ribbon any way you wish
— something that can’t be done at all via manual interaction.
Using VBA, you can also create a custom application that runs within the host application. For example,
you could create within PowerPoint a custom application that automatically creates a presentation for
you.
By using VBA, you can also access one application from another application. For example, Word can’t do
much in the way of mathematical calculations on sets of data similar to Excel. So, when working with
VBA from Word, you can write code that starts an Excel session, performs some calculations, and then
puts the results into a Word document. Similarly, when using VBA from Excel, you can export particular
objects to a new presentation that Excel created automatically in PowerPoint by using VBA. This way
you can see the power of using VBA.
Because VBA provides a standard set of tools that differ in capability according to the specializations of
the host application, once you’ve learned to use VBA in one application, you’ll be able to apply that
knowledge quickly to using VBA in another application.
As with any programming language, getting started with VBA involves a considerable learning effort, but
you can use the Macro Recorder tool built into several of the Microsoft Office applications (notably
Word and Excel) to reduce this effort considerably.
• You can record a macro that automatically carries out a series of actions that you frequently
perform. For example, you might need to insert a picture in a Word document, format it to give
it the right size and layout, and then add a caption under it, using the appropriate text style. Or
you might need to insert an Excel chart on a PowerPoint slide, format it, and add descriptive
text.
• You can write code that performs actions a certain number of times and that makes decisions
depending on the situation in which it is running. For example, you could write code that takes a
series of actions on every presentation that’s open in PowerPoint.
• You can interact with the user by creating forms, or custom dialog boxes, that enable the user to
make choices and specify settings for the code that’s running. For example, you might display a
set of formatting options— captioned controls such as check boxes and option buttons— that
the user can select. Then when the user closes the dialog box, your code can examine the status
(the properties) of these controls and take appropriate action.
• You can take actions via VBA that you can’t do (or do easily) by directly manipulating the user
interface. For example, when you’re working interactively in most applications, you’re limited to
working with the active file — the active document in Word, the active workbook in Excel, and
so on. By using VBA, you can manipulate files that aren’t active.
• You can make one application manipulate another application. For example, you can make
Word place a table from a document into an Excel worksheet.
Macros
A macro is a sequence (collection) of commands you can repeat at will. You can repeat these actions by
using a single command to run the macro. In some applications, you can also set a macro to run itself
automatically. You could run the macro either manually or automatically upon opening a document of
that type.
A macro is a type of subroutine (sometimes also called a subprocedure). Generally, people tend to use
the shorter, more informal terms sub, procedure, or routine. A macro is sometimes thought to consist of
recorded code rather than written code, but most people use the word in its wider sense, so it can
include written code as well. For example, if you record a macro and then edit it to make it more
efficient, or to add commands to make it take further actions, most people still consider it a macro.
In an application that supports the VBA Macro Recorder (such as Word or Excel), you can create macros
in two ways:
• Turn on the Macro Recorder and perform the sequence of actions you want the macro to
perform.
• Open the Visual Basic Editor and type the VBA commands into it.
In applications which do not support Macro Recorder, you will have to use the Visual Basic Editor (VBE)
to create your macro.
There’s also a useful hybrid approach that combines recording with editing. Just record the sequence of
actions, and then in the Visual Basic Editor, delete any unneeded commands. While editing the macro,
you can add other commands. You can also add user interface elements (such as message boxes and
dialog boxes), so users of the macro can make decisions and choose options for how to run it.
Once you’ve created a macro, you specify a way of running it. In most applications, you can assign a
macro to the Quick Access Toolbar or to a shortcut key combination and run it at any time. You can also
assign one of these ways of launching a macro when you record the macro, via a dialog box that
automatically appears when you begin the recording.
Recording a Macro
The easiest way to create VBA code is to record a macro using the Macro Recorder, but only some
applications support the Macro Recorder. You switch on the Macro Recorder, optionally assign a
method for running the macro (a toolbar button or a shortcut key combination), perform the actions
you want in the macro, and then switch off the Macro Recorder. As you perform the actions, the Macro
Recorder translates them into commands, or in other words, code, in the VBA programming language.
Once you finish recording the macro, you can view the code in the Visual Basic Editor and change it if
necessary. If the code works perfectly as you recorded it, you never have to look at it since you can just
run the macro at any time by choosing the assigned toolbar button or key combination, or by running it
directly from the Macros dialog box (click the Run button) or the Visual Basic Editor (press F5).
Before starting recording the macro you need to plan it. This is necessary to avoid problems that may
arise during the recording. For example, the application should be ready so that you can perform the set
of operations you are intending to record in the macro. However, there is a pause facility in the Macro
Recorder in some applications. This capability allows you to work around problems you hadn’t
anticipated when planning the macro. Some macros perform any necessary setup themselves. The
setup will be part of the macro. In these cases, you should make sure that the application is in the state
that the macro expects before you start recording the macro.
Macro Naming
Each macro must be given a name using which you can execute it. This name must be a multipart name
that explains what the macro does so that it will be much easy when you have a considerably large
collection of macros in hand. (Adding comments in the body of the macro –of course you will not see
them when you execute the macro - helps understand the macro at a later time). There are few rules
that must be observed when naming a macro. The name
• Must start with a letter; after that, it can contain both letters and numbers.
• Can be up to 80 characters long.
• Can contain underscores, which are useful for separating words, such as File Save.
• Cannot contain spaces, punctuation, or special characters, such as ! or *.
Storing a Macro
In Excel, you can choose to store the macro in This Workbook (the active workbook), a New Workbook,
or the Personal Macro Workbook. The Personal Macro Workbook is a special workbook named
PERSONAL.XLSB. Excel creates this Personal Macro Workbook the first time you choose to store a macro
in the Personal Macro Workbook. By keeping your macros and other customizations in the Personal
Macro Workbook, you can make them available to any of your procedures.
Excel stores each recorded macro for any given session in a new module named Modulen, where n is the
lowest unused number in ascending sequence (Module1, Module2, and so on). Any macros you create
in the next session go into a new module with the next available number. If you record macros
frequently with Excel, you’ll most likely need to consolidate the macros you want to keep so that they’re
not scattered in several modules like this.
• Specify the macro that you want to edit. The host application then opens the Visual Basic Editor
and displays the macro, so that you’re ready to work with it.
• Open the editor directly, and then locate the macro code you want to work with. The next two
sections demonstrate the two ways of opening the Visual Basic Editor, and the third section
shows you how to navigate to a macro.
If you know which macro you want to work with, you can open the Visual Basic Editor and the macro at
the same time. For this, you have to open the application that contains the macro, press Alt+F8 to
display the Macros dialog box, select the required macro and then click the Edit button in the dialog box.
The Visual Basic Editor will be opened with the macro displayed and ready for editing.
To open the Visual Basic Editor directly, too, you have to open or activate the host application. Then
press Alt+F11 (alternatively you can use the Visual Basic button in the Developer ribbon). The Visual
Basic Editor opens. After opening the Visual Basic Editor directly, use the Project Explorer pane to
navigate to your macro. You also use the Project Explorer to navigate among open projects and modules
when you’re working in the Visual Basic Editor. Once you open the module containing your macro, you
can double-click the module to open it in the VBE. If the module contains more than one macro, you’ll
also need to select the macro you want to work with. To select a macro, you can either select the macro
from the Procedure dropdown list in the Code window or use the scroll bar to scroll to the macro you
want to edit, which is identified by the word Sub, the name you gave it, and a pair of parentheses.
• Fix any problems in the way a macro you recorded is executing. For example, if you made a
misstep when recording the macro, the macro will keep performing that wrong instruction every
time you run it, unless you remove or change the instruction.
• Add further instructions to the macro to make it behave differently. This is a great way to get
started with VBA, because by making relatively simple changes to a recorded macro, you can
greatly increase its power and flexibility.
• Create new macros by writing them in the Visual Basic Editor instead of recording them. You can
write a new macro from scratch or cull parts of an existing macro, as appropriate.
When testing a macro, if the macro encounters an error and crashes, VBA displays an error message box
on screen and selects the offending statement in the Code window. You can then edit the statement to
fix the problem. Once the problem is fixed, you can step through (execute one instruction at a time) the
macro to check its operation. For this position the insertion point somewhere in the macro code that
you want to run and press F8 to step through the macro command by command. Each time you press
F8, one line of your VBA code will be executed. The Visual Basic Editor highlights each command as it’s
executed, and you can watch the effect in the application window to catch errors.
You can also use breakpoints for debugging a macro. A breakpoint is a toggle switch you set on a line of
code to tell VBA to stop executing the macro there. By using a breakpoint, you can run through known
functional parts of a macro at full speed and then stop where you want to begin watching the code
execute statement by statement because you suspect the bug is located there.
It is always helpful to have the Project Explorer and the Properties windows displayed in the editor
environment. Therefore, make sure that you have both these elements are displayed. Then you have to
set the Visual Basic Editor up to require variables to be declared explicitly, so that you must declare each
variable formally before you use it. Selecting the Require Variable Declaration check box on the Editor
page from the Options dialog box will make this adjustment. This setting makes the Visual Basic Editor
automatically enter an Option Explicit statement for all modules and user forms you create from now
on. And that statement causes the editor to check during runtime for any implicitly declared variables
and require that you declare them explicitly, like this:
The procedure you’ll create for Excel is short but helpful: when the user runs Excel, the procedure
maximizes the Excel window and opens the last file worked on. The procedure also illustrates some
useful techniques, including how to:
You have to first make sure that the Personal Macro Workbook is available. For this you have to create a
new empty macro and select Personal Macro Workbook as the “Store macro in” location of the Record
Macro dialog box. Excel will create the personal.xlsb automatically. When the Visual Basic Editor is
opened, there will be an additional VBA Project in the Project Explorer. Once this project is expanded
and then the Microsoft Excel Objects folder is expanded, there will be a ThisWorkbook item, which
represents the current workbook. Double-click the ThisWorkbook item to open its code sheet in a Code
window. The line:
Option Explicit
The Object dropdown list is at the upper-left corner of the Code window, and the Events dropdown list
is towards right of that. If you select Workbook from the Object dropdown list, the Events dropdown list
will by default select open. At this moment, the Visual Basic Editor automatically creates the stub of an
Open event for the Workbook object and places the insertion point on the blank line in between the
Private Sub and End Sub.
End Sub
At this point you can use the Object Browser to find out the properties you need to work with in order
to achieve some goal. On the other hand, when entering code into Visual Basic Editor, it provides auto
list facility for your convenience. When you type the object name followed by the period (to show that
the property belongs to the object), a list of all available properties and events of that object is displayed
as a dropdown list. You can simply enter the required property by selecting it using the mouse. Then you
can use the equal sign to assign the property value. The list of allowed values will popup when you type
the equal sign. Now consider the following procedure.
The object Application is used by VBA to identify Excel. WindowState represents the state of the window
(whether it is maximized, minimized or normal state). RecentFiles is a collection object that contains
details of the files in the recently used files list. RecentFiles(1) represents the first element in the
collection and that in turn represents the last file opened. Open is a method of that object. If you save
this procedure in the Personal Macro Workbook, then each time you start Excel, the window will be
maximized with the last opened file in it.
VBA Basics
Let’s have a brief look at how VBA programmes are created.
Procedures
A procedure in VBA is a named unit of code that contains a sequence of statements to be executed as a
group. The name assigned to the procedure gives you a way to refer to the procedure. All executable
code in VBA must be contained in a procedure — if it isn’t, VBA can’t execute it, and an error occurs.
Procedures are contained within modules, which in turn are contained within project files, templates, or
other VBA host objects, such as user forms.
Functions
A function in VBA is one of two types of procedures. A function is a type of complete procedure
designed to perform a specific task. For example, the Left function returns the left part of a text string,
and the Right function, its counterpart, returns the right part of a text string. Each function has a clear
task that you use it for, and it doesn’t do anything else.
VBA comes with many built-in functions, but you can also create your own. They will begin with a
Function statement and end with an End Function statement. Each function returns a value. For
example, the Left function returns the left part of the string. Other functions test a condition and return
True if the condition is met and False if it is not met.
Subprocedures
A subprocedure (also called a sub or subroutine) is a self-contained unit of code that doesn’t return a
value. All the macros you record using the Macro Recorder are subprocedures. Each subprocedure
begins with a Sub statement and ends with an End Sub statement.
Statements
When you program a macro in VBA, you’re writing statements, which are similar to sentences in
ordinary speech. A statement is a unit of code that describes an action, defines an item, or gives the
value of a variable. VBA usually has one statement per line of code, although you can put more than one
statement on a line by separating them with colons. (This isn’t usually a good idea, as it makes your code
harder to read.)
You can also break a line of code onto a second line or a subsequent line to make it easier to read by
using a line-continuation character: an underscore (_ ) preceded by a space (and followed by a carriage
return). You do so strictly for visual convenience; VBA still reads both lines, or all the continued lines, as
a single ‘‘virtual’’ line of code. In other words, no matter how many line continuations you use for
formatting, it’s still a single statement.
VBA statements vary widely in length and complexity. A statement can be a single word (such as Beep,
which makes the computer beep, or Stop, which halts the execution of VBA code) to very long and
complicated lines involving many components.
Keywords
A keyword is a word defined as part of the VBA language. Here are some examples:
• The Sub keyword indicates the beginning of a subprocedure, and the End Sub keywords mark
the end of a subprocedure.
• The Function keyword indicates the beginning of a function, and the End Function keywords
mark the end of a function.
• The Dim keyword starts a declaration (for example, of a variable) and the As keyword links the
item declared to its type, which is also a keyword. For example, in the declaration Dim
strExample As String, there are three keywords: Dim, As, and String.
Expressions
An expression consists of keywords, operators, variables, and constants combined to produce a string,
number, or object. For example, you could use an expression to run a calculation or to compare one
variable against another. Here’s an example of a numeric) that compares the variable N to the number 4
by using the > (greater than) operator:
If N > 4 Then
Operators
An operator is a symbol you use to compare, combine, or otherwise work with values in an expression.
VBA has four kinds of operators:
Variables
A variable is a location in memory set aside for storing a piece of information that can be changed while
a procedure is running. (Think of it as a named, resizable compartment within the memory area.) For
example, if you need the user to input their name via an input or a dialog box, you’ll typically store the
name in a variable so you can work with it in the procedure.
You can either let VBA create Variant variables in which to store your information, or you can specify
which type any given variable can be. Specifying the types of variable has certain advantages that you’ll
learn about in due course.
When you create a variable in VBA by typing the following line and pressing Enter:
Nothing visible happens, but VBA has created the myVariable variable. It has set aside some memory
and labeled that area myVariable. Now, type the following line and press Enter:
MsgBox myVariable
This time, you can see the result: VBA goes to the area you specified (with the variable name
myVariable) and retrieves the value. A message box appears containing the text you entered in the
variable.
You can declare variables either explicitly or implicitly. An explicit declaration specifies the name you
want to give the variable, and usually its type, before you use the variable in your code. An implicit
declaration occurs when you tell VBA to store data in a variable that you have not explicitly declared.
VBA then stores the data in a Variant variable.
In the next few chapters, you’ll use a few implicit variable declarations to keep things simple. You don’t
have to type in any code that declares implicit variables. VBA will create them for you when you first use
them in a statement. After that, you’ll start using explicit variable declarations to make your code run
faster and easier to read. Also, some types of errors can be avoided if you explicitly declare all variables.
Constants
A constant is a named item that keeps a constant value while a programis executing. The constant’s
meaning doesn’t change at different times of program execution. (It’s not a variable.) VBA uses two
types of constant: intrinsic constants, which are built into an application, and user-defined constants,
which you create. For example, the built-in constant vbOKCancel is used with the MsgBox function to
create a message box that contains an OK and a Cancel button. You might define a constant to store a
piece of information that doesn’t change, such as the name of a procedure, or the distance between
Boston and New York. In practice, built-in constants are used quite often; user-defined constants not so
much. It’s just as easy to put the distance between those cities in a variable.
Arguments
An argument is a piece of information— supplied by a constant, a variable, a literal, or an expression —
that you pass to a procedure, a function, or a method. Some arguments are required; others are
optional. As you saw earlier, the following statement uses the optional argument SaveChanges to
specify whether Excel should save any unsaved changes while closing the active workbook:
ActiveWorkbook.Close SaveChanges:=xlDoNotSaveChanges
The Visual Basic Editor’s helpful prompts and the Visual Basic Help file show the list of arguments for a
function, a procedure, or a method in parentheses, with any optional arguments enclosed in brackets. If
you have the Auto Quick Info feature activated, the Editor displays the argument list for a function,
procedure, or method after you type its name followed by a space.
• Enter the name of the argument (for example, UpdateLinks) followed by a colon and an equal
sign (UpdateLinks:=) and the constant or value you want to set for it (UpdateLinks:=True). For
example, the start of the statement might look like this:
• Enter the constant or value in the appropriate position in the argument list for the method,
without entering the name of the argument. The previous statement would look like this:
When you use the first approach— naming the arguments — you don’t need to put them in order,
because VBA looks at their names to identify them. You also don’t need to indicate to VBA which
arguments you’re omitting.
By contrast, when you don’t employ argument names, you’re specifying which argument is which by its
position in the list. Therefore, the arguments must be in the correct order for VBA to recognize them
correctly. If you choose not to use an optional argument but to use another optional argument that
follows it, enter a comma to denote the omitted argument. For example, the following statement omits
the UpdateLinks argument and uses a comma to denote that the False value refers to the ReadOnly
argument rather than the UpdateLinks argument:
When you type the comma in the Code window or the Immediate window, Auto Quick Info moves the
boldface to the next argument in the argument list to indicate that it’s next in line for your attention.
When you’re assigning the result of a function to a variable or other object, you enclose the whole
argument list in parentheses. For example, to assign to the variable objMyWorkbook the result of
opening the document c:\temp\Example.xlsm, use the following statement:
When you aren’t assigning the result of an operation to a variable or an object, you don’t need to use
the parentheses around the argument list, but it’s common practice to do so.
Objects
To VBA, each application consists of a series of objects. Here are a few examples:
Most of the actions you can take in VBA involve manipulating objects. For example, you can close the
active workbook in Excel by using the Close method on the ActiveWorkbook object:
ActiveWorkbook.Close
Collections
A collection is an object that contains several other objects. Collections provide a way to access all their
members at the same time. For example, the Workbooks collection contains all the open workbooks,
each of which is an object. Instead of closing Workbook objects one by one, you can close all open
workbooks by using the Close method on the Workbooks collection:
Workbooks.Close
Likewise, you can use a collection to change the properties of all the members of a collection
simultaneously.
Properties
Each object has a number of properties. For example, a document in Word has properties such as its
title, its subject, and its author. You can specify or edit these properties by clicking the Office button,
then clicking the Prepare link and clicking the Properties button (or press Alt+F, E, P).
Likewise, a single character has various properties, such as its font, font size, and various types of
emphasis (bold, italic, strikethrough, and so on).
Methods
A method is an action you can perform with an object. Loosely speaking, a method is a command.
Different objects have different methods associated with them— actions you can take with them or
commands you can specify that they perform. For example, the following methods are associated with
the Workbook object in Excel:
Activate Activates the document (the equivalent of selecting the document’s window with the
keyboard or mouse)
Close Closes the document (the equivalent of pressing Alt+F, C or clicking the Close button after
clicking the Office button)
Save Saves the document (the equivalent of pressing Alt+F, S or clicking the Save button after
clicking the Office button)
SaveAs Saves the document under a specified name (the equivalent of pressing Alt+F, A or clicking
the Save As button after clicking the Office button)
Events
An event is an occurrence that VBA recognizes as having happened, often something that happened to
an object. For example, the opening of a file (either by a user or by a procedure) typically generates an
event. The user’s clicking a button in a user form generates an event.
By writing code for an event, you can cause VBA to respond by taking actions when that event occurs.
For example, for a user form, you might write some code in an OK button’s click event. This code would
check that all necessary settings were specified by the user when the user clicked the OK button to
dismiss the user form and apply the settings. You would write additional code within that button’s click
event that responded (perhaps by displaying a message box) if the user had failed to type in some
required information.
Defining Data
A variable is a named area in memory that you use for storing data while a procedure is running. When
creating a variable, a memory area is reserved for the storage of the value of that variable. Later a value
can be put into that place using the name given to that variable. This value contained in the memory can
be then used again and again by the programme for various purposes.
Variable Naming
VBA imposes several constraints on variable names:
• Variable names must start with a letter and can be up to 255 characters in length.
• Variable names can’t contain characters such as periods, exclamation points, mathematical
operators (+, −, /, *), or comparison operators (=, <>, >, >=, <, <=); nor can they internally
contain type-declaration characters (@, &, $, #).
• Variable names can’t contain spaces but can contain underscores, which you can use to make
the variable names more readable.
Each variable name must be unique within the scope in which it is operating (to prevent VBA from
confusing it with any other variable). Typically, the scope within which a variable operates is a
procedure, but if you declare the variable as public or module-level private, its scope is wider.
The other constraint on variable names is that you should avoid assigning to a variable a name that VBA
already uses as the name of a function, a statement, or a method. Doing so is called shadowing a VBA
keyword. It doesn’t necessarily cause problems, but it may prevent you from using that function,
statement, or method without specifically identifying it to VBA by prefacing its name with VBA. For
example, instead of Date, you’d have to use VBA.Date.
Declaring a Variable
VBA lets you declare variables either implicitly or explicitly. Explicit declarations are almost always a
good idea. For this reason, it’s best to declare your variables explicitly right from the beginning.
Declaring a variable implicitly means that you just use it in your code without first declaring it explicitly.
When you declare a variable implicitly, VBA checks to make sure that there isn’t already an existing
variable with that name. It then automatically creates a variable with that name for you and assigns it
the Variant data type, which can contain any type of data except a fixed-length string. VBA usually
assigns the variable the value “Empty” (a special value used to indicate Variant variables that have never
been used) when it creates it.
The advantage of declaring a variable implicitly is that you don’t have to code it ahead of time. If you
want a variable, you can simply declare it on the spot. But declaring a variable implicitly also has a
couple of disadvantages:
• It’s easier to make a mistake when re-entering the name of an implicitly declared variable later
in the procedure. VBA doesn’t query the latter spelling with its typo but just creates another
variable with that name. When you’re working with a number of variables, it can be difficult and
time-consuming to catch little mistakes like these.
• The Variant variable type takes up more memory than other types of variable, because it has to
be able to store various types of data. This difference is negligible under most normal
circumstances, particularly if you’re using only a few variables or writing only short procedures.
However, if you’re using many variables on a computer with limited memory, the extra memory
used by Variant variables might slow down a procedure or even run the computer out of
memory. What’s more important on an underpowered computer is that manipulating Variants
takes longer than manipulating the other data types. This is because VBA has to keep checking
to see what sort of data is in the variable.
You can get around this second disadvantage by using a type-declaration character to specify the data
type. A type-declaration character is a character that you add to the end of a variable’s name in an
implicit declaration to tell VBA which data type to use for the variable
% Integer
& Long
@ Currency
! Single
# Double
$ String
Declaring a variable explicitly means telling VBA that the variable exists before you use it. VBA then
allocates memory space to that variable and registers it as a known quantity. You can also declare the
variable type at the same time.
You can declare a variable explicitly at any point in code before you use it, but custom and good sense
recommend declaring all your variables at the beginning of the procedure that uses them (or for
variables with greater scope, in the General Declarations area up at the top of the Code window).
Locating declarations at the top of a procedure makes them easy to find, which helps anyone reading
the code.
• Your code is easier to read and to debug. When you write complex code, this is an important
consideration.
• It will prevent you from creating new variables unintentionally by mistyping the names of
existing variables. It will also prevent you from wiping out the contents of an existing variable
unintentionally when trying to create a new variable.
• VBA can catch some data-typing errors at design time or compile time.
• Your code runs faster because VBA won’t need to determine each variable’s type at run-time.
To declare a variable explicitly, you use one of the following keywords: Dim, Private, Public, or Static.
Dim is the regular keyword to use for declaring a variable. You can also declare multiple variables on the
same line by separating the variable statements with commas.
Be warned that when you declare multiple variables on the same line, you need to specify the data type
for each variable declared.
The scope of a variable is the area in VBA within which it can operate. Typically, you’ll want to use a
variable with its default scope: within the procedure that declares the variable (either implicitly or
explicitly). The variables in each procedure are distinct from the variables in the other procedures, and
there is no danger of VBA confusing them.
The lifetime of a variable is the period during which VBA remembers the value of the variable. You need
different lifetimes for your variables for different purposes. A variable’s lifetime is tied to its scope.
Sometimes you need to access a variable from outside the procedure in which it’s declared. In these
cases, you need to declare a different, wider scope for the variable.
• Procedure
A variable with procedure scope (also known as procedure-level scope or local scope) is
available only to the procedure that contains it. As a result, the lifetime of a local variable is
limited to the duration of the procedure that declares it: as soon as that procedure stops
running, VBA removes all local variables from memory and reclaims the memory that held them.
Local variables don’t persist if execution moves outside their procedure.
• Private
A variable with private scope is available to all procedures in the module that contains it, but not
to procedures in other modules. Using private variables enables you to pass the value of a
variable from one procedure to another. Unlike local variables, which retain their value only as
long as the procedure that contains them is running, private variables retain their value as long
as the project that contains them is open. To declare a variable with private scope, you can use
either the Dim keyword or the Private keyword at the beginning of a module, placing it up top
before the Sub statement for the first procedure in the module
• Public
A variable with public scope is available to all procedures in all modules in the project that
contains it. To declare a public variable, you use the Public keyword in the declarations area at
the beginning of a module, before the Sub statement for the first procedure in the module. Like
private variables, public variables retain their value as long as the project that contains them is
open. Public variables are reset when the Visual Basic Editor recompiles code, so you’ll need to
reinitialize them after editing your code.
Static Variables
Beside declaring variables with Dim, Private, and Public, there’s also the Static keyword, which you can
use for declaring static variables — variables whose values you want to preserve between calls to the
procedure in which they are declared. Static variables are similar to public variables in that their lifetime
is not limited to the duration of the procedure that declares them. The difference is that static variables,
once declared, are available only to the procedure that declared them. Static variables have the scope of
a local variable but the lifetime of a Public or Private variable.
Static variables are useful for maintaining information on a process that you need to run a number of
times during a session of the application.
Data Types
Specifying the data type for each variable you create is a good idea, but it’s not compulsory. You can
almost always use the default Variant data type, however there are some disadvantages.
Arrays
An array is a variable that can contain a number of values that have the same data type. VBA treats an
array as a single variable that can store multiple values. You can refer to the array itself to work with all
the values it contains, or you can refer to the individual values stored within the array by using their
index numbers, which indicate their positions within the array.
Declaring an Array
An array is a kind of variable, so you would declare it by using the regular keywords: Dim, Private, Public,
or Static. To indicate that it’s an array, you add a pair of parentheses after the array’s name. If the data
type is not defined at the declaration, VBA creates a Variant array. VBA then assigns the appropriate
subtype or subtypes when you store data in the array.
You can specify the data type of the array just as for an ordinary variable. You can also declare the
number of items in the array by using an array subscript. VBA arrays are zero-based arrays, i.e., the array
subscript starts from 0, not 1. The first item has the subscript 0. To make numbering start at 1, add an
Option Base statement to the declarations area at the beginning of the module in which you declare the
array.
Multidimensional Arrays
When you declare an array with a single subscript you get a one-dimensional array, which is the easiest
kind of array to use. But VBA supports arrays with up to 60 dimensions. You probably won’t want to get
this complicated with arrays — two, three, or four dimensions are enough for most purposes.
To declare a multidimensional array, you separate the dimensions with commas. Multidimensional
arrays sound forbidding, but a two-dimensional array is quite straightforward if you think of it basically
as a table that consists of rows and columns.
To declare a dynamic array, you use a declaration statement without specifying the number of items (by
including the parentheses but leaving them empty).
Redimensioning an Array
You can change the size of, or redimension, a dynamic array by using the ReDim statement. When you
use ReDim to redimension an array like this, you lose the values currently in the array. If so far you’ve
only declared the array as a dynamic array, and it contains nothing, losing its contents won’t bother you;
but at other times, you’ll want to increase the size of an array while keeping its current contents. To
preserve the existing values in an array when you raise its upper bound, use a ReDim Preserve
statement instead of a straight ReDim statement. If you use ReDim Preserve to lower the upper bound
of the array, you lose the information stored in any subscripts not included in the redimensioned array.
For example, if you have a five-subscript array with information in each slot, and you redimension it
using ReDim Preserve so that it has only three subscripts, you lose the information in the fourth and fifth
subscripts.
Note that ReDim Preserve works only for the last dimension of the array. You can’t preserve the data in
other dimensions in a multidimensional array.
Erasing an Array
To erase the contents of an array, use the Erase statement with the name of the array. This statement
reinitializes the items in a fixed-size array and frees the memory taken by items in dynamic arrays
(completely erasing the array).
VBA provides several types of If statements suitable for making simple or complex decisions, as well as
the heavy-duty Select Case statement for efficiency when working with truly involved decisions.
Conditional expressions in VBA are constructed using the comparison operators and logical operators.
There are seven comparison operators in VBA. They are: = (Equal to), <> (Not equal to), < (Less than), >
(Greater than), <= (Less than or equal to), >= (Greater than or equal to), is (Is the same object variable
as). Additionally, VBA provides six logical operators. They are: And (Conjunction), Not (Negation), Or
(Disjunction), XOr (Exclusion), Eqv (Equivalence), Imp (Implication).
If Statements
As in most programming languages, If statements are among the most immediately useful and versatile
commands for making decisions in VBA.
• If… Then
Tells VBA to make the simplest of decisions: if the condition is met, execute the following
statement (or statements); if the condition isn’t met, skip to the line immediately following the
conditional block. An If block statement begins with If and concludes with End If. However, a
short If... Then statement can be written entirely on a single line, in which case the End If is
omitted.
• If... Then... Else
Often you’ll need to decide between two courses of action. To do so, you use the If... Then...
Else statement. By using an If... Then... Else statement, you can take one course of action if a
condition is True and another course of action if it’s False.
• If... Then... ElseIf... Else
Used to help VBA decide between multiple courses of action. You can use any number of ElseIf
lines, depending on how complex the condition is that you need to check. Again, you can create
either one-line If... Then... ElseIf... Else statements or block If... Then... ElseIf... Else statements.
However, in almost all cases, block If... Then... ElseIf... Else statements are easier to construct, to
read, and to debug. As with the other If statements, one-line If... Then... ElseIf... Else statements
don’t need an End If statement, but block If... Then... ElseIf... Else statements do need one.
The Select Case statement provides an effective alternative to multiple ElseIf statements, combining the
same decision-making capability with tighter and more efficient code. Many people also find Select Case
pretty easy to read.
Use the Select Case statement when the decision you need to make in the code depends on one variable
or expression that has more than three or four different values that you need to evaluate. This variable
or expression is known as the test case.
Select Case statements are easier to read than complex If. . . Then statements, mostly because there’s
less code. This also makes them easier to change: when you need to adjust one or more of the values
used, you have less code to wade through.
Repeating Actions
At times, you may want to repeat an action to achieve a certain effect. Sometimes, you’ll want to repeat
an action a predetermined number of times. More often, you’ll want to repeat an action until a certain
condition is met.
In VBA, you use loops to repeat actions. By using loops, you can transform a simple recorded macro into
one that repeats itself as appropriate for the material it’s working on. VBA provides a number of
expressions for creating loops in your code.
A loop is a structure that repeats a number of statements, looping back to the beginning of the structure
once it has finished executing them. Each cycle of execution of a loop is called an iteration.
For. . . Next loops repeat an action or a sequence of actions a given number of times, specified by a
counter variable. The counter variable can be hard-coded into the procedure, passed from an input box
or dialog box, or passed from a value generated either by a different part of the procedure or by a
different procedure.
[statements]
Next [counter]
The For Each. . . Next loop, which is unique to Visual Basic, has the same basic premise as the For. . .
Next loop, namely that you’re working with a known number of repetitions. In this case, though, the
known number is the number of objects in a collection.
VBA starts by evaluating the number of objects in the specified collection. It then executes the
statements in the loop for the first of those objects. When it reaches the Next keyword, it loops back to
the For Each line, re-evaluates the number of objects, and performs further iterations as appropriate.
You can use one or more Exit For statements to exit a For loop if a certain condition is met. Exit For
statements are optional and are seldom necessary. If you find yourself needing to use Exit For
statements in all your procedures, there’s probably something wrong with the loops you’re
constructing. That said, you may sometimes find Exit For statements useful — for example, for when an
error occurs in a procedure or when the user chooses to cancel a procedure.
Do loops give you more flexibility than For loops in that you can test for conditions in them and direct
the flow of the procedure accordingly. VBA includes several types of Do loops:
• Do While. . . Loop
• Do. . . Loop While
• Do Until. . . Loop
• Do. . . Loop Until
• Loops that test a condition before performing any action. Do While. . . Loop and Do Until. . .
Loop loops fall into this category.
• Loops that perform an action before testing a condition. Do. . . Loop While and Do. . . Loop Until
fall into this category.
The difference between the two types of loop in each category is that each While loop repeats itself
while a condition is True (until the condition becomes False), whereas each Until loop repeats itself until
a condition becomes True (while the condition remains False).
In a Do While. . . Loop loop, you specify a condition that has to remain True for the actions in the loop to
be executed. If the condition isn’t True, the actions aren’t executed and the loop ends.
Do While condition
[statements]
[Exit Do]
[statements]
Loop
A Do. . . Loop While loop is similar to a Do While. . . Loop, except that in the Do. . . Loop While loop, the
actions in the loop are executed at least once, whether the condition is True or False. If the condition is
True, the loop continues to run until the condition becomes False.
Do
[statements]
[Exit Do]
[statements]
Loop While condition
A Do Until. . . Loop loop is similar to a Do While. . . Loop loop, except that in a Do Until. . . Loop loop, the
loop runs while the condition is False and stops running when it’s True. Note that Do Until. . . Loop loops
are useful if you prefer to work with a condition that’s True and keep it looping until the condition
becomes False. Otherwise, you can achieve the same effects using Do While. . . Loop loops and inverting
the relative condition.
Do Until condition
statements
[Exit Do]
[statements]
Loop
The Do. . . Loop Until loop is similar to the Do Until. . . Loop loop, except that in the Do. . . Loop Until
loop, the actions in the loop are run at least once, whether the condition is True or False. If the condition
is False, the loop continues to run until the condition becomes True.
Do
[statements]
[Exit Do]
[statements]
Loop Until condition
You can use an Exit Do statement to exit a Do loop without executing the rest of the statements in it.
The Exit Do statement is optional, and you’ll probably seldom want to use Exit Do statements in your
loops — at least if the loops are properly designed. When you do need an Exit Do statement, you’ll
generally use it with a condition.
• The Workbooks collection contains the Workbook objects that represent all the open
workbooks. Within a workbook, the Sheets collection contains the Worksheet objects that
represent the worksheets and the Chart objects that represent chart sheets. On a sheet, the
Range object gives you access to ranges, which can be anything from an individual cell to a
complete worksheet.
• The ActiveWorkbook object represents the currently active workbook.
• The ActiveSheet object represents the active worksheet.
• The Windows collection contains the Window objects that represent all the open windows.
• The ActiveWindow object represents the active window. When using this object, be sure to
check that the window it represents is the type of window you want to manipulate, as the
object returns whatever window currently has the focus.
• The ActiveCell object represents, you guessed it, the active cell. This object is especially valuable
for simple procedures (for example, those that compute values or correct formatting) that work
on a cell selected by the user.
Creating a Workbook
To create a new workbook, use the Add method with the Workbooks collection. The syntax is as follows:
Workbooks.Add(Template)
To create a blank workbook (as if you’d clicked the Office button, then clicked the New button), omit the
Template argument:
Workbooks.Add
The new workbook receives the amount of sheets specified in the Excel Options’ Popular dialog box. You
can get or set this value in VBA by using the SheetsInNewWorkbook property of the Application object.
Example:
Workbooks.Add
Application.SheetsInNewWorkbook = mySiNW
End Sub
To save the workbook for the first time or with a different name, we can use,
ActiveWorkbook.SaveAs FileName:=”Filename.xlsx”.
If the file is already saved, just using, Workbooks(”Data Book.xlsx”).Save will save it under the current
name.
Each worksheet is represented by a Sheet object. The Sheet objects are contained within the Sheets
collection.
Inserting a Worksheet
To insert a worksheet into a workbook, use the Add method with the Sheets collection. The syntax is as
follows:
Example:
The ActiveCell property of the Application object or the Window object returns a Range object that
represents the active cell in the Excel application or in the specified window. If you use ActiveCell
without specifying the window, VBA returns the active cell in the active window.
For example, the following statement returns the address of the active cell in the active workbook:
ActiveCell.Address
The following statement returns the text in the active cell in the first window open on the workbook
named Planning.xlsx:
MsgBox Workbooks(”Planning.xlsx”).Windows(1).ActiveCell.Text
If no worksheet is active, or if a chart sheet is active, there is no active cell. If you try to access ActiveCell,
VBA returns an error. So before using code that assumes there is an active cell, check that ActiveCell is
not Nothing:
To return the value of the active cell, use the Value property. For example, the following statement sets
the value of the active cell to 25:
ActiveCell.Value = 25
In procedures that the user triggers, it’s often a good idea to return the active cell to where it was when
the user started the procedure. To do so, you can store the location of the active cell and then return it
to the stored location after your procedure is finished with its tasks. For example:
You can work with the range of cells around the active cell by using the CurrentRegion property to
return the CurrentRegion object. The current region extends from the active cell to the first blank row
above and below and to the first blank column to the left and right. For example, the following
statements use the Font property of the CurrentRegion object to set the font of the current region to
12-point Times New Roman with no bold or italics:
With ActiveCell.CurrentRegion.Font
.Name = ”Times New Roman”
.Size = 12
.Bold = False
.Italic = False
End With
Additionally, you can use macros to set various options of the application.
A module contains VBA code that’s organized into one or more procedures. A procedure is simply the
set of steps needed to perform some task. A new standard module contains no procedures because it’s
empty. Thus, the first step to writing code is to create a procedure.
Creating a Procedure
Adding a procedure to a module is a fairly simple task. The procedure that you create can be either a
Sub procedure or a Function procedure. A Sub procedure is like a command on a menu: when called, it
just does its job and doesn’t return anything. A Function procedure, on the other hand, is more like a
built-in function in that it returns a value. However, the steps for creating either type of procedure are
the same.
Macros in Word or Excel refer to a piece of VBA code that you would write in a module in Access. In
Access, a macro is a separate type of object, one that’s made up of a list of actions. Note that Word and
Excel also enable you to create your own modules. While Word and Excel have the capability to record
macros, Access does not. However, you can still create detailed macros using the Macro Editor in Access.
The only limitation is that you can’t record a macro; you must create it yourself step-by-step.
When you create your first macro the default name for your new macro is Macro1, but you should
change the name when you save the macro. There’s nothing inherently wrong with naming it Macro1,
but it doesn’t give you very much of a clue about what the macro is for. It is better to give your macro a
descriptive name.
It is similarly important to have a way to call the macro. One of the common uses for a macro and one of
the easiest ways to use one is in response to the click event of a command button on a form. To
associate a macro with the click event of a command button, you can use its OnClick property drop-
down list in the Property Sheet for the command button. (All macros in your database are included in
the drop-down list.) You can also call macros from within your code. If you already have a perfectly good
macro that does what you need, why not use it?
Every object in a database has a unique name. Most objects have properties and methods that VBA can
manipulate. The properties and methods exposed by an object are the steering wheels that allow VBA to
grab hold of an object and take control. The names that define all the objects that VBA can manipulate
are organized into an object model. Using VBA in Access is largely a matter of manipulating database
objects to achieve a goal.
The Access Object Model is a hierarchy of objects and collections. An object is a single ‘thing’ that can be
used in Access. On the other hand, a collection can contain many objects. Most of the objects can
themselves be a collection since it may contain other controls. (e.g. buttons on a form.) According to the
object model, Controls is both an object and a collection. Each control has its own collection of
properties that uniquely define its name and many other properties. You can see those properties in
form design when you select a single control and view its property sheet.
DBEngine.ParentCollection.ChildCollection!Object.Method_or_Property
Many DAO object collections contain still other collections, so it is sometimes necessary to drill down
through several collections before you get to the object that you want to operate on. This provides a
highly structured and predictable method for accessing data and schema.
With the exception of the DBEngine object, all DAO objects are contained within their own collections.
For example, the TableDef object is part of a TableDefs collection, and the Group object is part of a
DBEngine.Workspaces(0).Databases(0).TableDefs!tblPayments.Fields!PaymentDate.DefaultValue
As you can see, referring to objects, properties, and methods can sometimes result in quite long lines of
code. This can get pretty tedious after a while, so you can also refer to objects by their parent
collection’s default item. Assuming tblPayments is the first table in the TableDefs collection, and
PaymentDate is the first field in that table’s Fields collection, here is the shortened version:
DBEngine(0)(0)(0)(0).DefaultValue
The default item for any DAO object collection is the item that occupies ordinal position 0. This is in
contrast to VBA collections, in which the first member occupies position 1 — an important fact to
remember.
A workspace is a named user session that contains open databases and provides the facility for
transactions and (depending on the database format) user-and group-level security. As you can have
more than one workspace active at any time, the Workspaces collection is the repository for all the
workspaces that have been created.
You use the Microsoft Access workspace to access Microsoft Access database engine databases,
Microsoft Jet databases, and ODBC or installable ISAM data sources through the Microsoft Access
database engine.
The Workspace object contains three different object collections. These are Databases, Groups, and
Users. Note that the Groups and Users collections are hidden in Access 2007 and you’ll need to show
them in the Object Browser before they will appear using IntelliSense.
You don’t have to do anything to begin using a Microsoft Access workspace; Access creates one by
default.
You can use a workspace without appending it to the Workspaces collection, but you must refer to it
using the object variable to which it was assigned. You will not be able to refer to it through the
Workspaces collection until it is appended. To use the default workspace, you can either refer to it as
DBEngine(0), or create a reference to it in the same way you create references to other Access or DAO
objects. Because you’re not creating a new workspace object, there is no need to append it to the
Workspaces collection.
Using Transactions
A transaction is defined as a delimited set of changes that are performed on a database’s schema or
data. They increase the speed of actions that change data, and enable you to undo changes that have
not yet been committed.
Transactions offer a great deal of data integrity insurance for situations where an entire series of actions
must complete successfully, or not complete at all. This is the all-or-nothing principle that is employed in
most financial transactions.
For example, when your employer transfers your monthly salary from their bank to yours, two actions
actually occur. The first is a withdrawal from your employer’s account, and the second is a deposit into
yours. If the withdrawal completes, but for some reason, the deposit fails, you can argue until you’re
blue in the face, but your employer can prove that they paid you, and are not likely to want to do so
again. Similarly, your bank will not be too impressed if the withdrawal fails, but the deposit succeeds.
The reality is that the bank will take the money back, and you still end up with no salary. If, however, the
two actions are enclosed in a single transaction, they must both complete successfully, or the
transaction is deemed to have failed, and both actions are rolled back (reversed).
The first thing to remember about the DAO Errors collection is that it is not the same as the VBA.Err
object. The VBA.Err object is a single object that stores information about the last VBA error. The DAO
Errors collection stores information about the last DAO error.
Any operation performed on any DAO object can generate one or more errors. The DBEngine.Errors
collection stores all the error objects that are added as the result of an error that occurs during a single
DAO operation. Each Error object in the collection, therefore, contains information about only one error.
Having said that, some operations can generate multiple errors, in which case the lowest level error is
stored in the collection first, followed by the higher level errors. The last error object usually indicates
that the operation failed. Enumerating the Errors collection enables your error handling code to more
precisely determine the cause of the problem, and to take the most appropriate remedial action.
When a subsequent DAO operation generates an error, the Errors collection is cleared and a new set of
Error objects is added to the collection. One last point to note is that an error that occurs in an object
that has not yet been added to its collection, is not added to the DBEngine.Errors collection, because the
“object” is not considered to be an object until it is added to a collection. In such cases, the error
information will be available in the VBA.Err object.
Using DAO, you can have more than one database open in Access at any time. If you’re using an .accdb
or .mdb database file, you already have one database open (called the current database). Using the
Workspace object’s OpenDatabase method, you can open more than one database, and operate on
them under the same workspace context. Indeed, if you were to define more than one Workspace
object, you could have several databases open, each operating under a different workspace context. The
Databases collection contains and manages all databases currently open in the workspace.
Unless you’re working with an Access Data Project, when you create a database in Access, it is
automatically added to the Databases collection. Among its properties and methods, the Database
object contains five collections: TableDefs, Containers, QueryDefs, Recordsets, and Relations. In most
cases, you will be working with the default Microsoft Access database, which you can refer to using any
of the following syntaxes:
DBEngine.Workspaces(“#Default Workspace#“).Databases(0)
DBEngine.Workspaces(0).Databases(0)
DBEngine(0).Databases(0)
DBEngine(0)(0)
CurrentDb()
The current user’s default database is an object that you will use quite a lot. Although you can work with
it using any of the reference methods listed, in most cases it is often more convenient to assign it to an
object variable.
But far and away the most common method is to use the CurrentDb() function.
Access always maintains a single permanent reference to the current database. The first member of the
Databases collection is populated with a reference to the current database at start up. This reference,
pointed to by DBEngine(0)(0), is fine under most circumstances, but when, for example, you are working
on wizards, it is not always up-to-date. In these circumstances it is possible for the first database
collection member to point to something other than the default database. The chance of this occurring
in normal databases is negligible, but to ensure that you are working with the current database, you
need to execute the Refresh method, which rebuilds the collection, placing the current database in the
first position in the Databases collection.
1. Check if the table already exists, and if so, rename it. You could also choose to delete the table
instead of renaming it.
2. Create the table object using the Database’s CreateTableDef method.
3. Create the Field objects in memory, using the TableDef’s CreateField method, setting each
field’s attributes as appropriate.
4. Append each Field object to the TableDef’s Fields collection.
5. Append the TableDef object to the Database’s TableDefs collection.
6. Refresh the TableDefs collection to ensure it is up-to-date, and optionally call
Application.RefreshDatabaseWindow to refresh the Navigation pane.
Creating Indexes
Just creating the tables and fields isn’t enough. Eventually the tables are going to get pretty big, and
querying against them will take some time. To provide some measure of performance, you need to
create indexes because without proper indexes, the Access engine must scan the entire table to find the
records you want. Here’s the basic procedure for creating an index:
Before you create your first index, you should be aware of the following three things:
• Once an index is appended to its collection, its properties are read-only. Therefore, if you want
to change an index’s property after you’ve created it, you must delete the index and re-create it
with the new properties.
• Although you can give an index any name you like, when you create a primary key using the
Access Table Designer, it is automatically named PrimaryKey. To maintain consistency, it is wise
to give code-created primary keys the same name.
• Access databases do not support clustered indexes, so in Access workspaces and other
workspaces that connect to databases that use the Access database engine, the Index object’s
Clustered property is ignored.
Creating Relations
When you build a query with the graphical Query Designer, you are building a QueryDef object in the
default Access workspace. When you save the query, you are also appending a reference to it in the
QueryDefs collection. You can also build a QueryDef in code.
You can think of permanent (Access workspace) QueryDefs as SQL statements that are compiled the first
time they are executed. This is similar in concept to the way code is compiled. Once compiled,
permanent queries run marginally faster than temporary, unsaved queries, because Access does not
need to compile them before execution. Temporary QueryDefs are useful when you need to create their
SQL statements during runtime since you need to change its clauses depending on current operating
conditions or the value of some variable.
To create a QueryDef, execute the CreateQueryDef method against the Database object. If you set a
QueryDef’s Name property to something other than a zero-length string, it is automatically appended to
the QueryDefs collection, and saved to disk. Omitting the Name property, or explicitly setting it to a
zero-length string, results in a temporary (unsaved) QueryDef.
Once you have created a QueryDef, you can modify its properties as easily as you modify any other DAO
property. Deleting a QueryDef is simple. Just issue the Delete method against the QueryDefs collection.
Executing Queries
Queries that insert, update, or delete queries are known as action queries. While these types of queries
do not return records, it is common to run them using code.
There are three ways to programmatically execute a query: using the DoCmd.RunSQL method, the
object.Execute method, and the OpenRecordset method. The query argument for any of these methods
can either be the name of a permanent or temporary QueryDef, or a string expression that equates to a
query. When you want to execute a query when you open a recordset, specify the query name in the
Database object’s OpenRecordset method.
When you need to access and manipulate data one record at a time, you must use a Recordset object.
For this reason, recordsets are the workhorses of database programming. Four types of recordsets are
available in DAO. The one you use depends on where the data comes from, and what you want to do
with it.
Creating a Recordset
You can create a recordset by using the OpenRecordset method of the Database, TableDef, or QueryDef
objects:
The Source argument specifies the name of a table or query, or a string expression that equates to an
SQL query. For recordsets opened using the dbOpenTable type argument, the Source argument can only
be the name of a table.
The default recordset type that is opened if you omit the Type argument, depends on the type of table
you’re trying to open. If you open a Microsoft Access recordset on a local table, the default is a Table
type. If you open a Microsoft Access recordset against a linked table or query, the default type is
dynaset.
Whenever you work on records in a database, it is rare that you want to carry out an action on the
entire table. If you did, you would be best served by using an action query because queries operate
much faster on large numbers of rows than do row processing methods (recordsets). However, it is
more likely that you’ll want to do something with a subset of records, and that means you would need
to filter your query to select only those records that you wanted to work on.
With recordsets, you have the additional opportunity to sort the records, so you can operate on them in
a specific order, perhaps by ascending date, for example.
Filtering Records
Filtering is simply a way of restricting the number of rows returned by a recordset so that you can
minimize the amount of data you have to wade through. The additional benefit of filtering is that it also
reduces the amount of data that is sent across the network, thereby minimizing bandwidth usage.
You can filter a recordset using a WHERE clause in a query on which the recordset can be based, or in its
Source argument.
Of course, you can’t filter records on table-type recordsets because they load the entire table. You can,
however, filter dynaset- and snapshot-type recordsets.
Another method of filtering a recordset as it is being created is to use the Recordset object’s Filter
property. You can’t filter an existing recordset once it’s been created, so the filter won’t take effect until
you create a new recordset that is based on the first.
Ordering Records
Ordering is a way of defining how the data returned in the recordset is to be sorted. For example, you
might want to see, in ascending order of amount, a list of customers who owe you money.
There are three ways to sort recordsets: using the ORDER BY clause in a query on which the recordset
can be based, or in its Source argument; using the Index property; or using the Sort property. You can
only use the Index property on table-type recordsets, whereas the ORDER BY clause and Sort property
work only with dynaset- and snapshot-type recordsets.
Navigating Recordsets
Once you’ve opened a recordset, you’ll probably want to get at its data and you’ll probably want to
move from record to record.
DAO provides five methods and five properties to help you navigate through your recordsets. The
methods are Move, MoveFirst, MovePrevious, MoveNext, and MoveLast. The properties are
AbsolutePosition, PercentPosition, RecordCount, BOF (beginning of file), and EOF (end of file).
RecordCount
Given its name, you might assume that the RecordCount property actually indicates the number of
records returned by a recordset. That assumption is not quite accurate.
Recordsets do not always return their entire dataset immediately; they can take quite some time to
populate; the more rows they have to return, the longer they take. DAO returns a pointer to the
recordset early, so you can get on with doing whatever it is you want to do, assuming that the later rows
will have been returned by the time you get to them.
The RecordCount property actually returns the number of rows that the recordset has accessed so far.
Of course, if you issue the MoveLast method before checking RecordCount, the recordset does not
return until all the records have been accessed, in which case RecordCount then reports the correct
number of rows. In fact, that’s how you get an accurate record count, by issuing a MoveLast, followed
by checking the RecordCount property. Note that this technique does not work with forward-only
recordsets.
In terms of recordsets, a clone is a functional replica of the original. A clone of a recordset points to the
same data as the recordset it was copied from. Changes made to the data in the clone are reflected in
the original recordset. The difference is primarily in navigation. Using a cloned recordset, you can
navigate or search for data without moving the cursor in the original recordset. For example, you might
want to search for data in a form without changing the record position of the form. Using a clone, you
can perform the search, and then when you find the data you’re looking for, save the current Bookmark
for the clone. Once the Bookmark has been set, then set the Bookmark in the original recordset to move
its cursor.
Finding Records
you often need a way to find a specific record when working with recordsets. DAO provides two ways to
find a specific record: Seek and Find. The one you choose to use depends entirely on the type of
recordset you want to use it on.
To use Seek, you must specify three things: the name of the index to use (you can specify only one index
at a time), a comparison operator string (which can be <, <=, =, =>,or >), and one or more values that
correspond to the value of the key you’re looking for. You can specify up to 13 different key values.
Because the Find methods enable you to specify any field in the criteria, they may not be capable of
using a table’s indexes to execute a search. Compare this to the Seek method, which always uses a
table’s indexes to execute the search. Without an indexed field, the Find methods can just as easily use a
table scan to find the right record; it just depends on the type of search, and amount of data being
searched. Not surprisingly then, using the Find methods is usually far slower than using Seek.
A table scan is where the database engine must read each record as a part of a search. This often results
in a query or operation that is significantly slower than methods such as Seek. The Find methods can be
used on filtered dynaset and snapshot recordsets, which minimizes the number of records that have to
be searched.
In addition, because you have FindNext and FindPrevious methods at your disposal, you don’t have to
start at the beginning or end of the recordset to find subsequent matches; you can just keep searching
until you find the record you want.
On an open recordset, you return a field value by simply referring to it. There are, of course, several
ways to do this. The first method is to refer to the field by name. You can also refer to a field by the
recordset’s Field object.
Not all recordsets are editable, and the same can be said about some rows. Snapshot recordsets are
never editable, and user permissions and record locks can result in recordsets or individual rows that
you cannot edit. In addition, joins in some recordsets that are based on multiple tables can render the
entire recordset uneditable.
Adding Rows
The procedure for adding rows to a recordset is quite simple: Open the recordset, issue the recordset’s
AddNew method, make the additions, and then issue the Update method.
Editing Rows
The procedure for editing recordset data is also quite simple: Move to the row you want to edit, issue
the recordset’s Edit method, make the changes, and then issue the Update method.
Deleting Rows
Deleting rows is even simpler; you just move to the row you want to delete and issue the Delete
method. An important point to note when deleting rows is that as soon as you delete one, all the rows
above it shift down one position. This is of real consequence only if you are moving up through the
recordset (toward the end), deleting rows as you go. For example, if you wanted to delete a contiguous
set of rows, you could end up deleting every second row. This is because when you delete the current
row, the cursor does not move, but the rows above it move down one position to compensate.
Canceling an Edit
If you change your mind and decide not to continue adding or editing records, you can cancel the
update using the CancelUpdate method. You can only the cancel changes between the
AddNew...Update or Edit...Update methods.
As mentioned earlier, you can create an append-only field by setting the AppendOnly property of a
Memo field. In DAO, you can set the AppendOnly property of the Field2 object to True. When this
property is enabled, the memo field keeps its previous values as the data in the field is changed. This
happens regardless of whether you change the value in the Access interface or in DAO. In the Access
interface only the current value is displayed.
While this feature is very powerful, there isn’t a way to retrieve the history data for the field using DAO.
Fortunately, the Access Application object has a method named ColumnHistory to retrieve this data.
This, however, requires that Access is installed to retrieve this information. External applications will not
be able to retrieve this data.