1. Sales AVB2021
Orange Coast Database Associates
Visual Basic For Applications
MS Access, Intermediate Course
P.O. Box 6142
Laguna Niguel, CA 92607
949-489-1472
http://www.dhdursoassociates.com
2. Sales AVB2022
Orange Coast Database Associates
Loose association of local University
instructors and IT Professionals.
Started in 1996
Training
– On-site (custom classes for groups)
– Private desk side training for individuals
Consulting
Programming (incl. offshore)
3. Sales AVB2023
Post Class Contact Information
Contact: Dan D’Urso
Phone: 800-355-9855
Fax: 949-485-6284
Email: slides.1@dhdursoassociates.com
Web Sites:
– http://www.dhdursoassociates.com
– http://ocdatabases.itgo.com
4. Sales AVB2024
MS Access Introductory (100 Level)
Curriculum
AIN100
AIA101
AMP110
Macros
AIN104
Reports
& Forms
AIN102
Queries
AIN100T A, B
…See also AVB201/2 intermediate level VBA
6. Sales AVB2026
VBA Series
AVB201
– SESSION 1: Event driven Programming in Access
(3 hours).
– SESSION 2: VBA Language Constructs and Programming
Techniques (3 hours).
AVB202 (This class)
– SESSION 1: Working Programmatically with Data
(3 hours).
7. Sales AVB2027
Session 3: Working Programmatically
with Data (AVB202)
One 3 hour session
Three hands on exercises – students will program
data access three ways:
– SQL via ADO connection
– ADO
– Access DAO
Students will benefit from some prior exposure to
programming
8. Sales AVB2028
Session 3: Working Programmatically
with Data
Effectively referencing Access objects and
properties.
All About Me!
Fundamental SQL statements.
Referencing ADO.
Working with ADO Connections and Recordsets.
ADO vs. DAO.
9. Sales AVB2029
3.1 Effectively Referencing Access
Objects and Properties
Each object in Acccess (form, button, field, ..) has a unique
address by which it can be called. There are two operators that
you use:
the dot (.) and
the exclamation sign (!).
Example: Forms!frmProducts.Price
references the “Price” control on the form “frmProducts”.
10. Sales AVB20210
3.1 Effectively Referencing Access
Objects and Properties
Explanation: “frmProducts” name is preceded by a reserved
word “Forms” which identifies that following is the name of the
form (same name could be used for a report, which would then
belong to collection “Reports”).
Reserved words, other are Form, Reports, Screen and Me, are
always followed by a “!” sign.
Objects and their properties are connected with a dot “.”
character.
11. Sales AVB20211
..cont
NOTE: If controls or table fields are made up of more than
one word or they contain special characters, then names
must be enclosed in [ ] parenthesis.
Example: Forms!frmProducts![Product Price]
Using [ ] is safe, since they always work. If in doubt, use
them.
12. Sales AVB20212
3.2 All About Me!
“Me” is a shortcut for full object address.
Example: If we were accessing object (control) “Price” from a
procedure that is in form module behind the frmProducts
form, we could as easily use the
Me!Price
instead of the longer
Forms!frmProducts.Price.
“Me” is thus short for “Forms!frmProducts”.
NOTE: “Me!” always presents the address of the form or
report in which module it is used. “Me” has no meaning in
standard modules.
13. Sales AVB20213
3.3 Fundamental SQL Statements.
One of the great benefits of using VBA is the ability to
work directly with the underlying database tables, fields,
and records.
In any procedure or a function, SQL queries can be
combined with any other VBA code, all under complete
control of the programmer.
Multiple SQL statements can execute as part of the same
procedure, to perform complex operations, as we will see
in the comprehensive example of this session.
14. Sales AVB20214
..cont
Introducing the subject, we review some of the fundamental
operations we perform on tables and records:
Select (for record retrieval)
and action queries for
Update
Insert
and “Delete”
of records.
15. Sales AVB20215
..cont (SELECT statement)
“SELECT” statement has the richest syntax and is used to
retrieve records from one or multiple tables while at the same
time filter, sort, and in other way manipulate records and
values of fields in table(s).
SELECT Products.Description From Products Where
ProductId >3 Order By Description
would retrieve Description field from table Products, records
only those that have ProductId > 3 and remaining records
would be sorted alphabetically by the description text.
NOTE: One good way to learn the syntax of SELECT is to use
the query designer and check the resulting code under the
SQL view of the designer.
16. Sales AVB20216
..cont (action queries)
Exercise: Make one query in query designer for each action and
look at code in SQL view.
Delete From Products Where ProductId = 2
--Will delete one record from table Products.
Insert Into Products (SKU, Description, Price)
Values (123, “Using SQL” 12.99)
--Will insert one record into table Products.
UPDATE Products SET Products.Price = 10.00
WHERE ("ProductId“ = 2)
--Will update the price field of the record with ProductId = 2.
17. Sales AVB20217
3.4 Data Access Models
Access has 2 object models to work with data: ADO and DAO.
ADO is the newer technology so we cover it first.
DAO on the other hand is native to Access and has
some nice features that are not part of the ADO.
Prediction is DAO will not go away, despite the availability of
ADO.
18. Sales AVB20218
3.4 Referencing ADO (and/or DAO)
ADO = ActiveX Data Objects. It is an external library of
functions that has to be included as a reference to the project.
If your code is misbehaving, check the reference under the
VBA editor. By default, ADO and DAO libraries are both
referenced. Check anyway!
Go: Tools >> References in the editor.
DAO = Data Access Objects. More on DAO later.
20. Sales AVB20220
3.5 Working with ADO Connections
and Recordsets.
ADO is a rich object model which is best learned by
looking at examples. It lets you specify a
connection to the existing (or any other) database,
loop through the resulting recordset (in case the
SELECT statement was issued) and check for
properties of the recordset, such as: number of
records returned, where is the cursor, move back
and forth through the recordset, etc..
DEFINITION: Recordset is an in-memory copy of
the records returned by a query.
21. Sales AVB20221
3.5 Working with ADO Connections
and Recordsets.
Demonstration: Look at the procedure behind the
form “frmPerformance” and analyze the required
steps.
22. Sales AVB20222
..cont (ADO connections)
Most confusing to new ADO users are the properties used in the
recordset (rs) “Open” statement (last line).
Dim rs As New ADODB.Recordset
Dim cn As New ADODB.Connection
Set cn = CurrentProject.Connection
sqlString = “Select …….”
rs.Open sqlString, cn, adOpenDynamic, adLockOptimistic
rs.Open loads results specified in sqlString into the rs recordset
and uses the database connection cn to connect to the project’s
database. But what are the last 2 parameters??
23. Sales AVB20223
..cont (recordset properties)
..they are ADO constants specifying properties of the opened
recordset. The following table explains.
Cursor Type Lock Type Description
adOpenForwardOnly
(fire-hose cursor, fast)
adLockReadOnly
(can’t update DB)
(Default) You can only
scroll forward through
records. Disconnected.
adOpenDynamic
(flexible, yet slow)
adLockOptimistic
(updatable back to DB)
Any movement allowed.
DB Changes by other
users are visible.
Connected to DB.
adOpenStatic adLockReadOnly Any movement allowed
but disconnected from
the DB.
24. Sales AVB20224
..cont (comments on the example)
Example uses the “execute” method of the
connection object wherever we work with action
queries.
Execute method leverages the knowledge of SQL
and does not require any choices of locks and
cursor types.
25. Sales AVB20225
Using ADO Methods
Alternatively, there are Add, Update, and Delete methods of
the rs object available to perform the same thing:
1. rs.AddNew statement will insert a new record into the
existing recordset.
2. rs.Update will write record back to the database after you set
values of any fields in the record. This requires an updatable
recordset and thus you need to use the adOpenDynamic,
adLockOptimistic combo when opening the recordset.
3. rs.Delete will delete the current record. No additional call to
rs.Update is necessary.
26. Sales AVB20226
..cont (ADO Add and Update)
Use of ADO “Add” and “Update” methods: Insert a new
record into database table tblProducts.
Dim rs As New ADODB.Recordset
rs.Open “tblProducts”, CurrentProject.Connection,
adOpenDynamic, adLockOptimistic
rs.AddNew
rs(“Description”) = “Using SQL”
rs(“Price”) = 10.99
rs.Update
rs.Close
Set rs = Nothing
27. Sales AVB20227
..cont (ADO Delete)
Use of ADO “Delete” method: Delete record from database.
Dim rs As New ADODB.Recordset
sqlString = “Select * From tblProducts Where ProductId = “ & 1
rs.Open sqlString, CurrentProject.Connection, adOpenDynamic,
adLockOptimistic
If not rs.EOF Then rs.Delete
rs.Close
Set rs = Nothing
28. Sales AVB20228
..cont (ADO)
Exercise: Rewrite the main example with ADO
AddNew, Update, and Delete methods. In case of INSERT it
may be easier to work with.
29. Sales AVB20229
DAO
DAO allows working with database schema, groups, users,
permissions, etc.. while ADO does not. Beyond that, the
differences are mostly in syntax.
Microsoft does not plan any upgrades to DAO and
therefore using ADO is a preferred way for new projects
unless you can’t go without certain DAO features that are
omitted in ADO.
!! Advice: Decide on one object model (ADO or DAO) and
stick to it. Mixing both in the same project, while possible
even in the same procedure or function, can lead to much
confusion in your code.
30. Sales AVB20230
..cont
DAO has a database object which needs to be declared. ADO
makes this instance implicitly. This tells you right away,
which model is being used.
Dim db As Database
Set db = CurrentDb
Dim rs As DAO.Recordset
Dim sqlString As String
sqlString = “Select ….”
Set rs = db.OpenRecordset (sqlString, dbOpenSnapshot)
31. Sales AVB20231
..cont (navigation)
DAO has much same methods as ADO for navigating
recordset’s records:
MoveFirst
MovePrevious
MoveNext
MoveLast
And properties:
EOF, BOF, and RecordCount.
NOTE: rs.RecordCount can be a very useful property in both
ADO and DAO.
32. Sales AVB20232
..cont (DAO Add, & Update)
“SnapShot” recordset property of previous example
is not editable. It is an equivalent of adOpenStatic,
adLockReadOnly combo in ADO.
You need to use a dbOpenDynaset property for
updating.
33. Sales AVB20233
..cont (DAO Add, & Update)
Use of Add and Update methods (same as in ADO but rs is a
different type of object):
Set rs = db.OpenRecordset(“tblProducts”, dbOpenDynaset)
rs.AddNew
rs(“..”) = “..” ‘set some fields
…
rs.Update
NOTE: dbOpenDynaset property is equivalent to
adOpenDynamic, adLockOptimistic combo in ADO.
34. Sales AVB20234
..cont (DAO Delete, Conclusion)
Use of DAO “Delete” method is analogous to Add, Update
and the treatment in ADO.
Exercise: Try rewriting the “Make Report” procedure example
with DAO. There is no better teacher than extensive practice.
35. Sales AVB20235
..cont (DAO Delete, Conclusion)
Both ADO and DAO object models have tens of properties,
methods, and named constants. Chances are you will never
use most of them. But if you try to do something special, it
might just be worth checking into some reference to see if
what you are trying to do is already available and/or
supported. “Access 2003 VBA Programmers Reference” from
Wrox Press has good coverage of both models.
36. Sales AVB20236
THE END
Thank You for Attending the Course And
Wishing You a Happy VBA Programming !!
NOTE: If interested, check our schedule for
more Intermediate and Advanced VBA
Courses (coming soon!)
Editor's Notes
Demo: Procedure behind the “Make Report” button calculates performance (sales) based commissions for all sales people and stores results in a separate table. These results are further used by a query that generates a performance report.
Demo: Procedure behind the “Make Report” button calculates performance (sales) based commissions for all sales people and stores results in a separate table. These results are further used by a query that generates a performance report.