Visual Basic for Applications
Using Microsoft Access
What is VBA?
A Programming language that’s specifically
designed to work with the application
programs in Microsoft Office
Programmers use the term code to refer to
anything that’s written in computer
programming language.
Why VBA?
Greatly extends the functionality of macros
Allows customized interactions with users
Enables complex operations on records
Enables complete control over the Access
Object Model
Capable of making reports and forms that can
make decisions based on user choices,
databases data and user supplied values
Offers improved error handling capabilities
Events and Event Procedures
Event is when something happens to any
object in your application
Event Procedure is a piece of VBA code that is
associated with this object and this event.
Since event code is programmed, the event
can trigger any number actions.
In such event driven programming model, the
user is in control of when and what should
happen next in the application
Types of Events
Windows (Form, Report): opening, closing,
resizing
Data: making current, deleting, updating
Focus: activating, entering, exiting
Keyboard: pressing or releasing a key
Mouse: clicking a mouse button
Print: formatting, printing
Error and Timing: when error occurs in code
or some time passes
Commonly Used Events
Events are normally associated with a form,
report or some control on a form. Some
common form events are:
On Open
On Load
Before Update
On Unload
On Current
On Delete
Before Delete
Common Control Events
On Click
Before Update
After Update
On Double Click
Common Report Events
On Open
On Activate
On Close
On No Data
Event Flow
NOTE: A single user action can also trigger
several events that then run in succession.
For example, when the user opens a form,
all of the following events occur:
Open>>Load>>Resize>>Activate>>Current
Functions vs. Sub Procedures
Functions return a value to the calling code,
usually providing the result of the function’s
operation
Sub Procedure execute the code in the
procedure but do not return any values
Both, functions and procedures can accept
multiple input values from the calling
program that can be used inside their
respective operations.
Functions vs. Sub Procedures
Function Syntax:
Function FunctionName(passed Arguments) As “Data Type of Return”
…….some code
FunctionName = “ReturnValue”
End Function
Functions vs. Sub Procedures
Sub Procedure Syntax:
Sub SubName(Passed Arguments)
……some codes….
End Sub
Organizing VBA Code into Modules
All event procedures and any other VBA codes
are grouped and placed into “Modules”
MS Access has 4 types of modules: Standard,
Form, Report and Class
Each form and report has its own form or report
module. All event procedures associated with a
particular form or reports should reside in their
respective module
Standard module holds any other common or non
form/report specific code
Class modules support object oriented
programming approach (OOP) to development
Variables, Scope and Data Types
Variables are containers that hold data in programs
Each variable should have a type. VBA supports a
wide range of data types that are not identical to data
types declared on fields in tables. Knowing both
groups and how to map them is essential for good
programming
If you forget to assign type to a variable in VBA, then
the variable is treated as a “Variant”. Variants assume
data type when data is loaded in to the variable
NOTE: Avoid using VARIANTS. Execution is slower
Some Often Used Data Types in VBA
Boolean (True or False)
Currency (Formatted number $56.66)
Double, Single (51.23421)
Integer (332)
Date (#1/31/2016#)
String (“Any word or sentence”)
Scope of Variables (and Procedures)
Scope determines where can variable be
used. This depends on the place where and
also how it was declared.
Variables declared inside functions or subs
must be declared with a Dim Statement. They
are always local to that sub or function
Variables declared outside any function or sub
are always global to that module. Whether
they are also variable to other modules,
depends on what precede their declarations
with:
Scope of Variables (and Procedures)
“Private Area As Double” would be the same
as “Dim Area As Double”
“Public Area As Double” on the other hand is
global to the application
NOTE: You cannot use Public Declaration inside function or
sub. Use DIM only!!!!!
Scope of Variables (and Procedures)
Functions and Procedures also have a scope
Preceding function or procedure declaration
with a word “Public” or “Private” makes that
function of procedure available “in the module
where declared only” OR they can be called
from any place in the application
Built-In Functions and Procedures
Beside custom made functions and
procedures, there are some that are built-in
and part of the Access VBA language.
Built-in functions can be used anywhere in
your program
Built-In Functions Categories
Conversion (converts one data to another)
Date/Time
Financial
Mathematical
String Manipulation
Programming Check
Domain
Examples: Now(); Ucase(String);Round(3.78);Len(String)
DoCmd Methods
GotoRecord
Docmd.GoToRecord(ObjectType, ObjectName, Record, Offset)
OpenForm
DoCmd.OpenForm(FormName,View,FilterName,WhereCondition,DataMode,
WindowMode, OpenArgs)
OpenReport
Docmd.OpenReport(ReportName, View, FilterName, WhereCondition,
WindowMode, OpenArgs )
OpenQuery
DoCmd.OpenQuery(QueryName, View, DataMode)
Quit
DoCmd. Quit(Options)
Save
DoCmd.Save(ObjectType, ObjectName)
MsgBox Function
MsgBox(prompt,buttons,title,helpfile,context)
Argument Description
prompt Required. String expression displayed as the message in the dialog box. The maximum length
of prompt is approximately 1024 characters, depending on the width of the characters used.
If prompt consists of more than one line, you can separate the lines using a carriage return character
(Chr(13)), a linefeed character (Chr(10)), or carriage return – linefeed character combination
(Chr(13) & Chr(10)) between each line.
buttons Optional. numeric expression that is the sum of values specifying the number and type of buttons to
display, the icon style to use, the identity of the default button, and the modality of the message box. If
omitted, the default value for buttons is 0.
title Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application
name is placed in the title bar.
helpfile Optional. String expression that identifies the Help file to use to provide context-sensitive Help for the
dialog box. If helpfile is provided, context must also be provided.
context Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by
the Help author. If context is provided, helpfile must also be provided.
MsgBox Function
MsgBox(prompt,buttons,title,helpfile,context)
Constant Value Description
vbOKOnly 0 Display OK button
only.
vbOKCancel 1 Display OK and Cance
l buttons.
vbAbortRetryIgnore 2 Display Abort, Retry,
and Ignore buttons.
vbYesNoCancel 3 Display Yes, No,
and Cancel buttons.
vbYesNo 4 Display Yes and No b
uttons.
vbRetryCancel 5 Display Retry and Can
cel buttons.
MsgBox Function
MsgBox(prompt,buttons,title,helpfile,context)
Constant Value Description
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Using the WhereCondition Argument
DoCmd.OpenForm "Invoice", acNormal, , "OrderID = " & Me.OrderID
The "OrderID = " in the filter expression refers to the OrderID field in the
Invoice report's underlying query. The OrderID on the right side of the
expression refers to the value the user selected from the OrderID list in the
dialog box. The expression concatenates the two, causing the report to
include only the invoice for the record the user selected.
Me. – is the reference to the active form
Me.OrderId or Me!OrderID – reference to Field OrderID in the current Form
VBA Language Constructs &
Programming Techniques
Making Decisions
The “IF” programming construct is one of the
most useful programming language
structures. It lets your code make “smart”
decisions based on user input and state of
variables, IF statement comes few variants:
a. IF condition Then “do this”
b. IF condition Then
“do this”
ELSE
“do this”
END IF
Making Decisions
“Select…Case” construct can add significantly
to readability of the program. Use it
whenever there is large selection of actions
available.
Select Case “Test Expression”
Case 1
action 1
Case 2
action 2
Case 3
action 3
End Select
Making Repetitions
Some piece of code often needs to execute
more than once
The For..Next Loop
For variable = initial to Final
…do this…
Next variable
The Do..Loop
Do
…do this…
Loop While condition
Do While condition
…do this…
Loop
Calling Functions and Sub Procedures
Procedure calls can be as simple as stating
the name of the procedure or you can use
“Call Procedure_name” form
Procedures called by name are called without
parenthesis even when supplied with input
values. Values must be separated by a
comma. “Call” form requires parenthesis
Function calls need to be assigned to some
variable since they always return a value
Functions are always called with parenthesis.
No “call” form is available