Access VBA Introduction
Access VBA Introduction
VBA Introduction
Name
Address
MicrosoftTraining.net
In Access worksheets, tables, forms, reports and queries are also objects.
When working in VBA tell Access exactly what to do. Don’t assume anything.
Title bar, Menu bar The centre of the Visual basic environment. The
and Standard menu bar and toolbar can be hidden of customized.
toolbar
Closing this window closes the program.
Code Window Used to edit the Visual basic code. Press F7 and it
will open an object selected in Project Explorer.
Close the window with the Close button that
appears on the menu bar.
Alternatively use the Ask a Question box on the menu bar to as a quick way to
find help on a topic.
OR
Press Alt + Q
OR
Within a project you can create as many standard modules as required. You should
store related procedures together within the same module.
Standard modules are also used to declare global variables and constants.
Defining Procedures
A procedure is a named set of instructions that does something within the
application.
To execute the code in a procedure you refer to it by name from within another
procedure. This is known as Calling a procedure. When a procedure has finished
executing it returns control to the procedure from which it was called.
While rules must be followed or an error will result, conventions are there as a
guideline to make your code easier to follow and understand.
Use the proper case for the word within the procedure name
If procedures are related try and place the words that vary at the end of the
name
PrintClientList
GetDateStart
GetDateFinish
Creating a Sub-Procedure
Most Access tasks can be automated by creating procedures. This can be done by
either recording a macro or entering the code directly into the VB Editor’s Code
window.
Statement block
End Sub
Public indicates procedure can be called from within other modules. It is the
default setting
Private indicates the procedure is only available to other procedures in the same
module.
The Sub…End Sub structure can be typed directly into the code window or inserted
using the Add Procedure dialog box.
A function returns a value to the procedure that calls it. The value the function
generates is assigned to the name of the function.
[Statement block]
[FunctionName = <expression>]
End Function
Public indicates procedure can be called from within other modules. It is the
default setting
Private indicates the procedure is only available to other procedures in the same
module.
The As clause sets the data type of the function’s arguments and return value.
Calling Procedures
A sub procedure or function is called from the point in another procedure where
you want the code to execute. The procedure being called must be accessible to
the calling procedure. This means it must be in the same module or be declared
public.
Sub procedure
Function
procedure
When passing multiple arguments (as in the function procedure above) always
separate them with commas and pass them in the same order as they are listed in
the syntax.
Auto Quick Info is a feature of the Visual Basic that displays a syntax box when
you type a procedure or function name.
The example below shows the tip for the Message Box function:
OR
Press Ctrl+G.
To evaluate an expression:
Type ? Expression
Press Enter.
Within the code, especially in loops, use the Debug.Print statement to display
values in the Immediate window while the code is executing. The Immediate
window must be open for this.
Procedur
Object list Procedure list e
Select Options.
Require Variable Adds the line Option Explicit to all newly created modules,
Declaration requiring all variables to be explicitly declared before they are
used in a statement.
Auto List Displays a list box under your insertion point after you type an
Members identifiable object. The list shows all members of the object class.
An item selected from the list can be inserted into your code by
pressing the Tab key
Auto Quick Info Displays a syntax box showing a list of arguments when a
method, procedure or function name is typed
Auto Data Tips Displays the value of a variable when you point to it with a mouse
during break mode. Useful for debugging.
Auto Indent Indent the specified amount when Tab is pressed and indents all
subsequent lines at the same level.
Drag-and-Drop Text Editing Allows you to drag and drop code around the Code
window and into other windows like the Immediate
window.
Default to Full Module View Displays all module procedures in one list with
optional separator lines between each procedure.
The alternative is to show one procedure at a time,
as selected through the Procedure list.
Editing Guidelines
Strings that are continued require a closing quote, an ampersand (&), and a
space before the underscore. This is called Command Line Continuation.
When focus is moved off the code line, the code formatter automatically
places key words in the proper case, adjusts spacing, adds punctuation and
standardizes variable capitalization.
Start the line with an apostrophe ( ‘ ) or by typing the key word Rem (for remark).
When using an apostrophe to create a comment, you can place the comment at
the end of a line containing a code statement without causing a syntax error.
Defining Objects
Objects are defined by lists of Properties, and Methods. Many also allow for
custom sub-procedures to be executed in response to Events.
The term Class refers to the general structure of an object. The class is a template
that defines the elements that all objects within that class share.
Properties
Properties are the characteristics of an object. The data values assigned to
properties describe a specific instance of an object.
A new Form in Access is an instance of a Form object, created by you, based on the
Form class. Properties that define an instance of a Form object would include its
Name, Caption, Size, etc.
Methods
Printing a report, updating a record and running a query are all examples of actions
that can be executed using a method.
Events
Many objects can recognize and respond to events. For each event the object
recognizes you can write a sub procedure that will execute when the specific event
occurs.
A Form recognizes the Open event. Code inserted into the Open event procedure
of the Form will run whenever the Form is opened.
Events may be initiated by users, other objects, or code statements. Many objects
are designed to respond to multiple events.
The Application object represents the application itself. All other objects are below
it and accessible through it. It is by referencing these objects, in code, that we are
able to control Access.
Objects, their properties and methods are referred to in code using the “dot”
operator as illustrated below:
The Forms collection in Access represents a set of all open Forms. An item in the
collection can be referenced using an index number or its name.
The following syntax references an object in a collection by using its position. Since
the Item property is the default property of a collection there is no need to include
it in the syntax.
Forms(1)
Reports(7)
CollectionName(ObjectName)
Forms(“Employees”)
Reports(“Sales Report”)
The Object Browser is often the best tool to use when you are searching for
information about an object such as:
Press F2 OR
Click
ObjectReference.PropertyName
Form.Name
ObjectReference.PropertyName = expression
Form.Name = “Quarterly Sales 2006”
The With statement helps optimize the code because too many “dots” in the code
slows down execution.
With ObjectName
<Statement>
End With
With recordset
.movefirst
.movenext
.edit
End With
Make sure that the code does not jump out of the With block before the End With
statement executes. This can lead to unexpected results.
Some methods require arguments that must be supplied when using the method.
ObjectReference.Method [argument]
Forms(2).Open
Recordset.movelast
When calling procedures or methods that have arguments you have two choices
of how to list the argument values to be sent.
Values can be passed by listing them in the same order as the argument list. This
is known as a Positional Argument.
Alternatively you can pass values by naming each argument together with the value
to pass. This is known as a Named Argument. When using this method it is not
necessary to match the argument order or insert commas as placeholders in the
list of optional arguments
Argumentname:= value
Sub PrintOut([From],[To],[Copies],[Preview],[ActivePrinter],[PrintToFile],[Collate],
[PrToFilename])
The statements below show both ways of passing values when calling the PrintOut
method. The first passes by Position, the second by Naming.
Event procedure names are created automatically. They consist of the object,
followed by an underscore and the event name. These names cannot be changed.
Event procedures are stored in the class module associated with the object for
which they are written.
Display the
code
window for
the
appropriate
class
module
Select the
event from
the
Procedure
drop-down
list
Enter the
desired
code in the
Event
Procedure
Expressions
An expression is a language element that, alone or in combination represents a
value. The different expression types typical of Visual basic are as follows:
Statements are entered one per line and cannot span more than one line unless
the line continuation character ( _ ) is used.
Statements combine the language’s key words with expressions to get things done.
Label(1).Caption = ActiveCell.Value
To declare a variable you give it a name. Visual Basic associates the name with a
location in memory where the variable is stored.
VariableName = expression
StdCounter = StdCounter + 1
You can force VBA to require explicit declaration be placing the statement Option
Explicit at the very top of your code module, above any procedure declaration.
With this statement in place, a Compiler Error - Variable Not Defined message
would appear when you attempt to run the code, and this makes it clear that you
have a problem. This way you can fix the problem immediately.
Although this forces you to declare variables, there are many advantages. If you
have the wrong spelling for your variable, VBE will tell you. You are always sure that
your variables are considered by VBE.
The best thing to do is tell the VBA Editor to include this statement in every new
module. See Setting Code Editor Options on Page 21.
Important Note
When you declare more than one variable on a single line, each variable must be
given its own type declaration. The declaration for one variable does not affect the
type of any other variable. For example, the declaration:
Dim X, Y, Z As Single
It IS the same as
For clarity, always declare each variable on a separate line of code, each with
an explicit data type.
The choice of data type will impact the programs accuracy, efficiency, memory
usage and its vulnerability to errors.
The structure and size of the memory storage unit that will hold the
variable
The kind and range of values the variable can contain. For example in the
Integer data type you cannot store other characters or fractions
The operations that can be performed with the variable such as add or
subtract.
Important Info
If data type is omitted or the variable is not declared a generic type called Variant
is used as default.
Excessive use of the Variant data type makes the application slow because Variants
consume lots of memory and need greater value and type checks.
Numeric data types provide memory appropriate for storing and working on
numbers. You should select the smallest type that will hold the intended data so
as to speed up execution and conserve memory.
Operations inside parentheses ( ) are performed first. Access evaluates the operators
from left to right.
The following numeric operations are shown in order of precedence and can be used in
with numeric data types.
Divide and Multiply ( / *) Multiply and divide with floating point result
4.94065645841247E-324 to
1.79769313486232E308 for positive
values
Important Info
For monetary values with up to 4 decimal places use the Currency data type.
Single and Double data types can be affected by small rounding errors.
A numeric variable of any type may be stored to a numeric variable of another type.
The fractional part of a Single or Double will be rounded off when stored to an
Integer type variable.
Procedure-Level Variables
These are probably the best known and widely used variables. They are declared
(Dim or Static) inside the Procedure itself. Only the procedure that contains the
variable declaration can use it. As soon as the Procedure finishes, the variable is
destroyed.
Module-Level Variables
These are variables that are declared (Dim or Private) outside the Procedure itself
in the Declarations section of a module.
By default, variables declared with the Dim statement in the Declarations section
are scoped as private. However, by preceding the variable with the Private
keyword, the scope is obvious in your code.
All variables declared at this level are available to all Procedures within the Module.
Its value is retained unless the variable is referenced outside its scope, the
Workbook closes or the End Statement is used.
Public Variables
These variables are declared at the top of any standard Public module. Public
variables are available to all procedures in all modules in a project
Public procedures, variables, and constants defined in other than standard or class
modules, such as Form modules or Report modules, are not available to
referencing projects, because these modules are private to the project in which
they reside.
1. Local (Dim)
2. Module-Level (Private, Dim)
3. Public (Public)
Private Mod1A
Procedure Private Frm1C
Procedure Procedure D
Procedure B
Dim B1
Intrinsic functions appear as methods in the Object Browser. To view and use
them:
For further help on a particular function, display the Visual Basic Help window.
On the Contents tab:
VBA has many built-in constants that can be used in expressions. VBA constants
begin with the letters vb while constants belonging to the Access object library
begin with xl.
To access Intrinsic constants in the Object Browser follow the steps below:
vbLf
Soft return and linefeed
+
vbCrLf Combination of carriage return
and linefeed
For a full list of Visual Basic Constants, search Help for VB Constants while in the
Visual Basic Editor.
The MsgBox Function can display a variety of buttons, icons and custom title bar
text.
The MsgBox Function can be used to return a constant value that represents the
button clicked by user.
Both MsgBox Functions above produce a message box with 2 buttons, a text
message, an icon and a title as shown below:
Sub Example()
Dim X As Integer
X=2
End Sub
The Msgbox message must be a string (text), hence the Str() function is
required to convert an integer to a string which is concatenated with the first
string using the & operator.
title Optional. String expression displayed in the title bar of the dialog box.
If you omit title “Microsoft Access” is the default title
helpfile Optional. String expression that identifies the Help file to use for the
input box. If helpfile is provided, context must also be provided.
The values and constants for creating buttons are shown below:
The values for setting the default command button are shown below:
The values for controlling the modality of the message box are shown below:
To display the OK and Cancel buttons with the Stop icon and the second button
(Cancel) set as default, the argument would be:
273 (1 + 16 +256).
It is easier to sum the constants than writing the actual values themselves:
Return Values
The MsgBox Function returns the value of the button that is clicked. Again this
can be referenced by the number or the corresponding constant.
OK vbOK 1
Cancel vbCancel 2
Abort vbAbort 3
Retry vbRetry 4
Ignore vbIgnore 5
Yes vbYes 6
No vbNo 7
The return value is of no interest when the MsgBox only displays the OK button.
In this case just call the MsgBox Function with the syntax used to call a sub
procedure as shown below:
Or
The InputBox Function prompts the user for a piece of information and returns
it as a string.
In the example the return value of the function is being stored in a variable called
strEmpID.
If OK is clicked, the function returns the contents of the text box or a zero-length
string, if nothing is entered.
If the user clicks Cancel, it returns a zero-length string, which may cause an error
in the procedure if a value is required.
title Optional. String expression displayed in the title bar of the dialog
box. If you omit title “Microsoft Access is the default title.
helpfile Optional. String expression that identifies the Help file to use for
the Input box. If helpfile is provided, context must also be
provided.
Errors are called Bugs. The process of removing bugs is known as Debugging. VBA
provides tools to help see how the code is running.
Syntax Errors
Syntax errors occur when code is entered incorrectly and is typically discovered by
the line editor or the compiler.
Discovered by Line Editor: When you move off a line of code in the Code
window, the syntax of the line is checked. If an error is detected the whole
line turns red by default indicating the line needs to be changed.
Discovered by Compiler: While the line editor checks one line at a time,
the compiler checks all the lines in each procedure and all declarations
within the project. If Option Explicit is set, the compiler also checks that
all variables are declared and that all objects have references to the correct
methods, properties and events. The compiler also checks that all required
statements are present, for example that each If has an End If. When the
compiler finds an error it displays a message box describing the error.
Run-Time Errors
When a program is running and it encounters a line of code that it cannot be
executed, a run-time error is generated. These errors occur when a certain
condition exists. A condition could run fine 10 times but cause an error on the
11th. When a run-time error occurs, execution is halted a message box appears
defining the error.
Logic Errors
Any time you use division that contains a variable in the denominator, test
the denominator to ensure that it doesn’t equal zero
Test procedures with large data sets representing all possible permutations
of reasonable or unreasonable data. Make your procedure fail before
someone else does.
The toolbar buttons as they appear left to right are explained below:
Reset Clears the execution stack and module level variables and
resets the project.
Locals Window Displays the value of variables and properties during code
execution
VBA has the Locals Window, Immediate Window, Watch Window and Quick
Watch, described in Using Debugging Tools on the previous page, which can be
used to find the values of expressions
Another quick way of finding out the value of variables and expressions is the
Auto Data Tip which displays the value of the expression where the mouse is
pointing.
Setting Breakpoints
Setting breakpoints allows you to identify the location where you want your
program to enter into break mode. The program runs to the line of code and
stops. The code window displays and the line of code where the break point is
set is highlighted.
When the code is halted, the value of a variable or expression can be checked by
holding the mouse pointer over the expression or in the immediate window.
To set a breakpoint open the code window and select the desired procedure:
OR
During code execution the program can enter into Break Mode either intentionally
Click the Debug button to display the code window with the offending line
highlighted.
If during the program execution you need to intervene, for example it’s stuck in
an endless loop, you can do so by pressing Ctrl + Break or the Break button in
That action will suspend the program execution and produce the following
message:
Good error handling should keep the program from terminating when an error
occurs.
For a list of trappable errors in Access search Help for Trappable Errors
Constants while in the Visual Basic Editor.
Once an On Error statement has trapped an error, the error needs to be handled.
Below are the 3 basic styles that VBA uses for handling errors:
Use in-line error handling Use the On Error Resume Next statement to
trap the error. Then enter code to check for
errors immediately following any statements
expected to generate errors.
On Error GoTo 0
This statement disables the error-handling for the procedure at least until another
On Error statement is encountered. This is an alternative to changing the Error
Trapping settings to Break on All Errors as it only affects the procedure it is in.
Once the issue is resolved remove the statement from the procedure.
The properties of the Err object contain information such as the Error Number,
Description, and Source.
The Err object's Raise method is used to generate errors, and its Clear method is
used to remove any existing error information.
Using the Raise methods to force an error can help in error testing routines.
Err.Raise 11
The routine is always stored at the bottom of the procedure, preceded by an Exit
statement that prevents the routine from being executed unless an error has
occurred.
The benefit of using this style is that all the error-handling logic is at the bottom
rather than being mixed up with the main logic of the procedure making the
procedure easier to read and understand.
Dim A As Double
Dim B As Double
MsgBox A / B
Exit Sub
ErrorHandler:
If Err.Number = 11 Then
B = InputBox(Err.Description & " is not allowed. Enter a non-zero number.")
Resume
Else
MsgBox "Unexpected Error. Type " & Err.Description
End If
End Sub
When an execution has passed into an error routine the following list shows how
to specify which code to be used next:
End Sub / End Function Used to exit the procedure normally by reaching
the End Sub or end Function command
Using this method you place the code to handle errors directly into the body of
the procedure, rather than placing it at the end of the routine.
To do this, place the On Error Resume Next statement into the procedure. The
error handling code is then placed immediately after the line where the code is
expected to cause error. This method may be simpler to use in very long
procedures where two or more errors are anticipated.
Sub ProcFileOpen()
Err.Clear
End Sub
Firstname = “Alan”
= Equal to
When testing for more than one condition Boolean expressions can be joined
with a Logical Operator.
The block form is used when several statements are to be executed based on
result of the test condition:
If <condition> Then
<statement block>
End If
Like the If…Then structure the If…Then…Else structure passes control to the
statement block that follows the Then keyword when the condition is True and
passes control to the statement block that follows the Else keyword when the
condition is False.
If <condition> Then
<statement block>
Else
<statement block>
End If
End If
If <condition_1> Then
<statementBlock1>
[ElseIf <condition_2> Then
[<StatementBlock2>]]
[ElseIf <condition_3> Then
[<StatementBlock3>]]
[ElseIf <condition_N> Then
[<StatementBlockN>]]
End If
End If
Do While <condition>
<statement block>
[Exit Do]
Loop
Do Until <condition>
<statement block>
[Exit Do]
Loop
To perform the statement block at least once, use one of the following:
Do
<statement block>
[Exit Do]
Loop While <condition>
Do
<statement block>
[Exit Do]
Loop Until <condition>
Do
Count = Count +1
Loop Until Count = NoStudents
Use To
Repeat a statement block a specific
For…Next number of times. The number is known or
calculated at the beginning of the loop
and doesn’t change.
For…Each Repeat a statement block for each
element in a collection or array.
For…Next Repeat a statement block while working
through a list when the number of list
items is known or is calculated
beforehand.
Do…Loop Repeat a statement block while working
through a list when the number of list
items is not known or are likely to change.
Do…Loop Repeat a statement block while a
condition is met.
While working on a form the toolbox is displayed but becomes hidden when
another window in the Visual Basic Editor is selected. Controls are added to
forms to build a desired interface and add functionality.
The default set of controls, from left to right, on the above toolbox are described
below:
Toggle Button Creates a toggle button that when selected indicates a Yes,
True or On status.
Scroll Bar Creates a tool that returns a value of for a different control
according to the position of the scroll box on the scroll bar
All forms share the same basic set of properties. Initially every form is the same.
As you change the form visually, in the Form window, you are also changing its
properties. For example if you resize a form window, you change the Height and
Width properties.
The following list describes the more commonly used properties of a Form:
Property Description
MousePointer Sets the shape of the mouse pointer when the mouse
is positioned over the form.
All Forms share a set of events they recognize and to which they respond by
executing a procedure. You create the code to execute for a form event the same
way as you create other event procedures:
Object Procedur
Methods
Forms also share methods that can be used to execute built-in procedures.
Methods are normally used to perform an action in the form.
Use the keyword Me in the Form’s code module instead of its name to refer to
the active form and access its properties and methods.
Control properties can be viewed and assigned manually via the Properties window.
While each type of control is unique many share similar attributes.
The following list contains properties that are common among several controls:
Property Description
MousePointer Sets the shape of the mouse pointer when the mouse is
positioned over the object
TabIndex Determines the order in which the user tabs through the
controls on a form.
Click Occurs when the user clicks the mouse button while the
pointer is on the control
Naming Conventions
It’s a good practice to use a prefix that identifies the control type when you assign
a name to the control.
Object Prefix
Frame fra
Image img
Label lbl
Property Description
Property Description
Command buttons are used to get feedback from the user. Command buttons
are among the most important controls for initiating event procedures.
The most used event associated with the Command Button is the Click event.
Property Description
The Combo Box control allows you to display a list of items in a drop-down list
box. The user can select a choice from the list or type an entry.
The items displayed on the list can be added in code using the AddItem method.
Property Description
ListRows Sets the number of rows that will display in the list.
Text Returns or sets the text of the selected row on the list.
Some important methods that belong to the Combo Box are explained below:
AddItem item_name, index Adds the specific item to the bottom of the
list.
Option buttons is a frame are mutually exclusive, which means when one is
set to true the others will be set to false.
The Value property of the button indicates the on and off state.
Using Control Appearance
The Form toolbar provides several tools that are used to manipulate the
appearance of the controls on the form.
Many of the tools on the Form toolbar require the user to select multiple controls.
To do this:
Click the first control
Hold down the Shift key
Click any additional controls
Controls will be aligned or sized according to the first control selected. The first
control selected is identified by its white selection handles.
Send to Ungrou
Filling a Control
A list box or combo box control placed on the form is not functional until the
data that will appear on the list is added.
This is done by writing code in the sub procedure associated with the Initialize
event. This triggers when the form is loaded. The AddItem method is used to
specify the text that appears in the list.
The code below shows items added to a combo box named cboCourses:
With cboCourses
.AddItem “Excel”
.AddItem “Word”
.AddItem “PowerPoint”
End With
As seen, forms and their controls are capable of responding to various events.
Adding code to forms and control events are accomplished the same way as
adding code to events of other objects.
FormName.Show
frmNewData.Show
VBA is the programming language you use to interact with the Access Object
Model. To interact with the data in a database, you will need to use a data access
object model.
Access employs two such object models; Data Access Objects and ActiveX Data
Objects.
DAO allows you to work with and manipulate the records in table and queries
within an access database
Critical objects
Object Use
Database It is necessary to define the database that you are working
with.
We are primarily concerned with manipulating existing data. For this we are
primarily concerned with using the Recordset object
Tasks Description
Opening Dbs.OpenRecordset(“Table1”,
dbOpenTable)
Critical objects
Object Use
Database It is necessary to define the connection that you are
Connection working with also if it is the current database
Dim CN as ADODB.Connection
Set cn = CurrentProject.Connection
Dim rs as ADODB.Recordset
and now you can open the recordset based on the SQL
string
Tasks Description
Moving through a recordset MoveFirst Moves to first
record
MoveLast Moves to last
record
MoveNext Move to next
record
MovePrevious Move to previous
record
Editing a recordset Edit Prepares a record
for editing
Update Commits the
changes made to
a record
Adding to a recordset Append Adds new data as
a new record
Dim cn As ADODB.Connection
Dim rs As ADODB.recordset
Set cn = CurrentProject.Connection
rs.MoveFirst
Do Until rs.EOF
rs.MoveNext
rs.Close
Set rs = Nothing
End Sub
Sub ChangeProductPrices()
Dim rs As ADODB.recordset
Dim cn As ADODB.Connection
Set cn = CurrentProject.Connection
DoCmd.SetWarnings False
rs.MoveFirst
End If
rs.MoveNext
Loop
DoCmd.SetWarnings True
rs.Close
End Sub
E&OE
STL Training reserves the right to revise this publication and make changes from
time to time in its content without notice.