SlideShare a Scribd company logo
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
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)
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
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
Sales AVB2025
MS Access VBA (200 Level)
Curriculum
AVB201
Introduction
AVB201
DAO/ADO
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).
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
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.
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”.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Sales AVB20219
3.4 Referencing ADO (and/or DAO)
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.
Sales AVB20221
3.5 Working with ADO Connections
and Recordsets.
Demonstration: Look at the procedure behind the
form “frmPerformance” and analyze the required
steps.
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??
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.
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.
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.
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
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
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.
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.
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)
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.
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.
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.
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.
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.
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!)

More Related Content

PPTX
Microsoft dynamics ax 2012 development introduction part 2/3
PDF
Report programming model for microsoft dynamics ax 2012
PPT
VB6 Using ADO Data Control
PPT
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
PPTX
Microsoft dynamics ax2012 : forms and tables methods call sequences, How To?
PPTX
Microsoft Dynamics AX 2012 - Development Introduction Training - Part 3/3
PPT
SAS Proc SQL
PDF
Sq lite module7
Microsoft dynamics ax 2012 development introduction part 2/3
Report programming model for microsoft dynamics ax 2012
VB6 Using ADO Data Control
SQL202.2 Accelerated Introduction to SQL Using SQL Server Module 2
Microsoft dynamics ax2012 : forms and tables methods call sequences, How To?
Microsoft Dynamics AX 2012 - Development Introduction Training - Part 3/3
SAS Proc SQL
Sq lite module7

What's hot (20)

PDF
Visualbasic tutorial
DOCX
Fahri tugas cloud1
PDF
X++ advanced course
PPT
Sas Enterprise Guide A Revolutionary Tool
PDF
Sap abap tutorial 1 (1)
DOCX
Axapta interview questions
PPTX
Practical guide to SQL basics
PPTX
PDF
카카오커머스를 지탱하는 Angular
PDF
Proc sql tips
PPT
Reading Fixed And Varying Data
PDF
Sq lite module8
DOCX
Simple ado program by visual studio
PDF
Sq lite module6
PDF
Data warehousing unit 3.2
PDF
Creating a repository using the oracle business intelligence administration tool
PPT
DOCX
OBIEE publisher with Report creation - Tutorial
DOC
Complete Sql Server querries
Visualbasic tutorial
Fahri tugas cloud1
X++ advanced course
Sas Enterprise Guide A Revolutionary Tool
Sap abap tutorial 1 (1)
Axapta interview questions
Practical guide to SQL basics
카카오커머스를 지탱하는 Angular
Proc sql tips
Reading Fixed And Varying Data
Sq lite module8
Simple ado program by visual studio
Sq lite module6
Data warehousing unit 3.2
Creating a repository using the oracle business intelligence administration tool
OBIEE publisher with Report creation - Tutorial
Complete Sql Server querries
Ad

Viewers also liked (20)

PPT
Test 1
PDF
Presentatie REC 250309
PPT
Pharma Powerpoint 2
PPTX
PDF
IntelliStick
PDF
Resume Portfolio Linkedin 01 2009
PPT
Creating a Photo Story With Soundslides
PDF
青年創業及圓夢網 創業稅務大小事【創業懶人包 】
PDF
My Logo Portfolio
PPT
Comic Book
PDF
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
PDF
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
PPT
Displays
PPT
Ikregeer Overheid20
 
PPT
Dutch Overheid20
 
PPTX
minggu 2
PPTX
Show Your Work: Cheap & Easy Tools for Presenting Data
PPT
eParticipation in The Netherlands
 
PPTX
Tutorial: Your First Reporting Assignment
PDF
Course Catalog
Test 1
Presentatie REC 250309
Pharma Powerpoint 2
IntelliStick
Resume Portfolio Linkedin 01 2009
Creating a Photo Story With Soundslides
青年創業及圓夢網 創業稅務大小事【創業懶人包 】
My Logo Portfolio
Comic Book
The Future-Present Interrelationship: Reflections, Thoughts, And Ideas, As We...
Futuretronium Book 100.0 (The Revolution II)! By Andres Agostini at http://li...
Displays
Ikregeer Overheid20
 
Dutch Overheid20
 
minggu 2
Show Your Work: Cheap & Easy Tools for Presenting Data
eParticipation in The Netherlands
 
Tutorial: Your First Reporting Assignment
Course Catalog
Ad

Similar to AVB202 Intermediate Microsoft Access VBA (20)

PPTX
ECDL module 5: using databases [To be continued]
PPT
Lecture02 abap on line
PPTX
MS Access teaching powerpoint tasks
PPTX
Ado object
PDF
Ado.Net
PPT
vishual basic data base Pankaj
PPTX
Data base connectivity and flex grid in vb
PDF
PPTX
Module 08 Access & Use Database Application.pptx
PPTX
Access ppt
PPTX
Welcome-slides-durham-tech
PPT
AVB201.1 Microsoft Access VBA Module 1
PPTX
Operate Spreadsheet applications ppt.pptx
POTX
SOC_MSAccess_Infographic. A visual tour of the main ideas behind Access
PPT
Access 2010
PPTX
2.3.1 creating database, table and relationship on Access 2003
DOCX
Product Supplier59,58,8,2.50CIS 3100 - Database Desig.docx
DOCX
CIS 3100 - Database Design and ImplementationScoring Rubric.docx
PDF
Access Tutorial
PDF
Access tutorial
ECDL module 5: using databases [To be continued]
Lecture02 abap on line
MS Access teaching powerpoint tasks
Ado object
Ado.Net
vishual basic data base Pankaj
Data base connectivity and flex grid in vb
Module 08 Access & Use Database Application.pptx
Access ppt
Welcome-slides-durham-tech
AVB201.1 Microsoft Access VBA Module 1
Operate Spreadsheet applications ppt.pptx
SOC_MSAccess_Infographic. A visual tour of the main ideas behind Access
Access 2010
2.3.1 creating database, table and relationship on Access 2003
Product Supplier59,58,8,2.50CIS 3100 - Database Desig.docx
CIS 3100 - Database Design and ImplementationScoring Rubric.docx
Access Tutorial
Access tutorial

More from Dan D'Urso (20)

PPT
SQL201S Accelerated Introduction to MySQL Queries
PPT
LCD201d Database Diagramming with Lucidchart
PPTX
Database Normalization
PPT
VIS201d Visio Database Diagramming
PPT
PRJ101a Project 2013 Accelerated
PPT
PRJ101xl Project Libre Basic Training
PPT
Introduction to coding using Python
PPTX
Stem conference
PDF
SQL200A Microsoft Access SQL Design
PPTX
Microsoft access self joins
PDF
SQL302 Intermediate SQL
PDF
AIN106 Access Reporting and Analysis
PPT
SQL302 Intermediate SQL Workshop 3
PPT
SQL302 Intermediate SQL Workshop 2
PDF
Course Catalog
PPT
SQL302 Intermediate SQL Workshop 1
PDF
SQL212 Oracle SQL Manual
PDF
SQL201W MySQL SQL Manual
PDF
AIN100
PPT
SQL206 SQL Median
SQL201S Accelerated Introduction to MySQL Queries
LCD201d Database Diagramming with Lucidchart
Database Normalization
VIS201d Visio Database Diagramming
PRJ101a Project 2013 Accelerated
PRJ101xl Project Libre Basic Training
Introduction to coding using Python
Stem conference
SQL200A Microsoft Access SQL Design
Microsoft access self joins
SQL302 Intermediate SQL
AIN106 Access Reporting and Analysis
SQL302 Intermediate SQL Workshop 3
SQL302 Intermediate SQL Workshop 2
Course Catalog
SQL302 Intermediate SQL Workshop 1
SQL212 Oracle SQL Manual
SQL201W MySQL SQL Manual
AIN100
SQL206 SQL Median

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mushroom cultivation and it's methods.pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
1. Introduction to Computer Programming.pptx
PDF
Getting Started with Data Integration: FME Form 101
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation theory and applications.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Tartificialntelligence_presentation.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Univ-Connecticut-ChatGPT-Presentaion.pdf
Unlocking AI with Model Context Protocol (MCP)
Mushroom cultivation and it's methods.pdf
A comparative analysis of optical character recognition models for extracting...
1. Introduction to Computer Programming.pptx
Getting Started with Data Integration: FME Form 101
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Assigned Numbers - 2025 - Bluetooth® Document
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
Encapsulation theory and applications.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Tartificialntelligence_presentation.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

AVB202 Intermediate Microsoft Access VBA

  • 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: [email protected]  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
  • 5. Sales AVB2025 MS Access VBA (200 Level) Curriculum AVB201 Introduction AVB201 DAO/ADO
  • 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.
  • 19. Sales AVB20219 3.4 Referencing ADO (and/or DAO)
  • 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

  • #21: 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.
  • #22: 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.