Connecting To Microsoft Access Database From Excel VBA, Using DAO Object Model
Connecting To Microsoft Access Database From Excel VBA, Using DAO Object Model
Object Model
Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model
Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases
from Excel using VBA.
Part 1 of 3
Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases from Excel
using VBA
1. Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model.
2. Microsoft Access DAO Object Model: Create an Index, Create Relationship between Fields, Create and
Execute a Query.
3. Microsoft Access DAO Object Model: Import or Export Data from Access to Excel.
Contents:
Connect with Databases using DAO, RDO and ADO Objects
DAO Objects & Programming model
The DBEngine object & Workspace Object
DAO Databases
Tables of a DAO Database
Fields / Columns of a Table
Recordset & Records of a DAO Database Table
-----------------------------------------------------------------------------------
This section explains using the DAO Objects & Programming model to Connect with Access Databases from
Microsoft Excel, the DBEngine object, Workspace Object & Workspaces Collection, DAO Databases, Tables of
a DAO Database, Fields / Columns of a Table, Recordset & Records of a DAO Database Table, with practical
examples.
Connect with Databases using DAO, RDO and ADO Objects
To connect with other databases, when working in VBA, you can use either DAO (Data Access Objects), RDO
(Remote Data Objects) or ADO (ActiveX Data Objects). After connecting to a database, you can manipulate its
data.
DAO, RDO and ADO are data access interfaces ie. they are object and programming models used to access
data. Earlier, DAO was used to interface with local databases (viz. MS Access), RDO was used to interface with
large databases such as Oracle and SQL Server. ADO was their replacement to interface with all types of data
sources. Both DAO and ADO are commonly used while connecting to Microsoft Access Database.
DAO is native to Access, the DAO object library is the default reference in Access 2007 and the library will be
existing when you use Access (ADO object library was the default reference in Access 2000 and 2002, whereas
DAO returned as the default object library with Access 2003 after being the default in Access 97 earlier). DAO
integrates well with Access databases and provides faster access. ADO provides access to a wider variety of
data sources than DAO, besides Access. ADO has succeeded DAO and is the latest data access technology, is
simpler and more flexible, and interfaces with Microsoft's powerful data access technology of OLE DB. In ADO
the objects are less than in DAO, and it contains more properties, methods and events. ADO/OLE DB is
recommended for new projects but it might not be worthwhile to convert DAO code to ADO for existing projects.
ADO creates a reference to the database using the Connection object, to connect to the data source. You use
the Open and Close methods to open and close a Connection object. DAO creates a reference to the database
using the database object, to connect to the data source.
In Microsoft Access, Recordset objects are used to access and manipulate data in a database. A Recordset
object represents a set of records in a database table, or a set of records returned from running a query. Both
DAO and ADO libraries have a Recordset object, though the methods, properties, and options of the respective
object is different. A Record object is one row of data in a Recordset. A Recordset object has a Fields collection
which contains all the Field objects, where each Field object represents a column in the Recordset. In other
words, each record represents a row of data and contains many fields, and each field corresponds to a column
in the database table.
In your VBA code, you should ideally precede the object name by its program ID (ProgID) prefix, which in ADO
is "ADODB" and in DAO is "DAO". Many objects, for example the Recordset object, have similar names in both
DAO and ADO and it is advisable to have explicit references in your project. This becomes a must if you have
included references to both the DAO and ADO libraries in your VBA project, else the object library mentioned
first in the References list will prevail, resulting in confusion in the vba code.
While instantiating the Recordset object, you should use:
Dim daoRecSet As DAO.Recordset
Dim adoRecSet As ADODB.Recordset
instead of:
Dim RecSet As Recordset
DAO Objects & Programming model
DAO (Data Access Objects) is an object-oriented data access interface, used to connect to and access
databases. It was the first Objects & Programming model which used the Microsoft Jet database engine, and is
optimized to work Microsoft Access files (.mdb). The objects and collections in the DAO object hierarchy are
used to connect to a database, access and manipulate its data and database structure.
A database engine is the underlying software component of a database used to manipulate its data. DAO
Object Model by default uses the Microsoft Jet database engine for data access. ODBCDirect (which came after
ODBC) allowed DAO to access ODBC data sources directly without using the Jet database engine. In this
section we will illustrate connecting to Microsoft Access Database using DAO with the Jet engine. Prior to
Access 2007, Access used the Microsoft (JET) engine, but with Access 2007 the new and improved ACE
engine has succeeded and replaced JET. The ACE engine is fully backward-compatible so that it can be used
with the .accdb files (Access 2007) and the earlier .mdb files.
Automating Access from Excel: You can connect to and access a database using DAO, from external
applications which support automation (viz. MS Excel, MS Word, etc.), and in this section we show how to do
this from Microsoft Excel by using VBA. With automation you can control another application (MS Access)
within your host application (MS Excel) without any manual intervention. Automation is used typically to run
macros or queries from Excel to connect to or create or manipulate MS Access database and its structure, to
access and manipulate MS Access data and reports, to import data from MS Access to Excel for creating charts
and pivot tables and otherwise use the data for calculations and analysis.
ODBC (Open Database Connectivity):
ODBC (Open Database Connectivity) is an interface which enables an application to connect and access a
relational database, using the SQL query syntax. An ODBC database is a DBMS (Database Management
System) for which there is an appropriate ODBC driver (examples of DBMS include SQL Server, Oracle,
AS/400, Foxpro, Microsoft Access). The ODBC Driver is a software that resides between the ODBC Client
(which is the front-end application wherein the driver is loaded) and the DBMS (wherein the data is stored for
access), and it translates the command into a format that is understood by the DBMS. DAO Object Model uses
the Microsoft Jet database engine and is optimized to work Microsoft Access files (.mdb), but ODBC databases
can also be accessed with DAO and the Microsoft Jet database engine. A database engine is the underlying
software component of a database used to manipulate its data. Jet (Joint Engine Technology) is used by
Microsoft Access as its database engine.
OLE DB and ODBC:
OLE DB was intended as a successor to improve on ODBC by providing an enhanced and faster interface for
data access. OLE DB is not bound to the SQL language like ODBC and it supports all forms of data sources (ie.
relational and non-relational data sources including mainframe and hierarchical databases, e-mail and file
systems, text and graphical data, custom business objects, ...) whereas ODBC was limited to relational
databases. OLE DB was complex to be used directly with Visual Basic and Microsoft's ADO (ActiveX Data
Objects) Object Model was introduced which interfaces with an OLE DB provider and enables an application
(viz. Excel) to access and manipulate data from a database (viz. MS Access).
ODBC vs DAO, ADO vs DAO:
When working with ODBC data sources, use ODBC. With ODBC you can access any data source for which
there is an appropriate ODBC driver for the database you want to access. Examples of ODBC databases
include Oracle, Microsoft SQL Server, Microsoft Visual FoxPro, IBM DB2, Microsoft Access. When working with
Microsoft Jet (.mdb) databases, using DAO will be more efficient. Examples of Microsoft Jet databases include
Micorsoft Access, Microsoft SQL Server, Paradox. DAO Object Model uses the Microsoft Jet database engine
and is optimized to work Microsoft Access files (.mdb), but ODBC databases can also be accessed with DAO
and the Microsoft Jet database engine when you want the Jet database engine's speed and DAO's extra
functionality. DAO precedes ADO and ODBC precedes OLE DB. ADO/OLE DB is recommended for new
projects but it might not be worthwhile to convert DAO code to ADO for existing projects.
Add a reference to the DAO Object Library
To use DAO in your VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE, and then choose an appropriate version (mostly, you should
choose the highest version number), which is "Microsoft DAO 3.6 Object Library" for Access 2000 onwards.
The DBEngine object
The highest level object in the DAO object model is the DBEngine object, and it contains all objects in the
hierarchy of DAO objects. There can only be one DBEngine object and there is no collection of which it is an
element of. The DBEngine object has many properties and methods, and contains 2 collections - the
Workspaces collection and the Errors collection. You can configure the database engine with properties and
methods provided by the DBEngine object. A database engine is the underlying software component of a
database used to manipulate its data. You can refer to DBEngine directly without explicitly declaring an object
variable of type DBEngine.
Workspace Object & Workspaces Collection
Create a Workspace object to define a user session by name, in which a user performs all database
operations by using the Microsoft Access database engine. The Workspace object allows you to open multiple
databases or connections in a session, and you can open additional sessions with the Workspace object. A
Workspace session starts on creation of a new Workspace object and ends when the Workspace object Close
method is used. Multiple sessions (ie. workspace objects) are specifically useful when you want to perform
operations as different users or when you want to manage separate and independent operations in each
session. All active and unhidden workspace objects are called the Workspaces collection, which is contained in
the DBEngine object. In DAO, when you open databases, they automatically exist within the default workspace
which is the first workspace in the Workspaces collection. A default workspace, DBEngine.Workspaces(0), is
automatically created when a Workspace object is first referred to or used, with the name as "#Default
Workspace#", and if security is not enabled with username as "admin" (if security is implemented then
username is set to the name of the user who logs on).
You can use the CreateWorkspace method to create a Workspace object. It is not necessary to append a
Workspace object to the Wokspaces collection after creating it, and in this case you will need to refer it by the
object variable used in the CreateWorkspace method. It will be required to append a Workspace object to the
Wokspaces collection after creating it, if you want to refer to it from the Workspaces collection by its ordinal
number or Name viz. DBEngine.Workspaces(0) or DBEngine.Workspaces("WorkspaceObjectName") or
DBEngine.Workspaces![WorkspaceObjectName]. All defined DAO Workspace objects appended to the
collection comprise the Workspaces collection. There are 2 types of Workspace objects, as defined by
WorkspaceTypeEnum Enumeration in the CreateWorkspace method - (i) Microsoft Jet Workspace objects (type
- 'dbUseJet') which creates a Microsoft Access workspace; and (ii) ODBCDirect workspaces (type -
'dbUseODBC') which are not supported in Microsoft Office Access 2007. In this section we will discuss only
the Microsoft Jet Workspace objects.
By default the DBEngine.DefaultUser Property is set to "Admin" and the DBEngine.DefaultPassword Property is
set to a zero-length string ("") and the default Workspace object's user and password are defined accordingly.
When you start Access or access an Access database with vba, all users automatically log-in with the default
name "Admin" and the password of zero-length string (""), but to access a database in a secured system (ie. a
secured Access Database) users must provide a username and a password (if a password has been assigned
to the user). In a secured system, for the default workspace you set the DefaultUser and DefaultPassword
properties (for the DBEngine object), and after the default session has been initialized, additional sessions can
be created with user names and passwords. Note that password is case-sensitive but not the username. In this
section we do not go into further details of accessing a secured Microsoft Access database.
DBEngine.CreateWorkspace Method
Use the DBEngine.CreateWorkspace Method to create a new Workspace object. Syntax:
DBEngineObject.CreateWorkspace(Name, UserName, Password, UseType). All arguments, except
UseType, are mandatory. In the Name argument, specify a unique Workspace name for a session. In the
UserName argument, specify the name of the user for identification. In the Password argument, you are
required to enter a password for the Workspace object with a maximum of 20 characters. The UseType
argument specifies one of the WorkspaceTypeEnum values: (i) dbUseJet - (Microsoft Jet Workspace objects)
which creates a Microsoft Access workspace, and is also the default; and (ii) dbUseODBC - for ODBCDirect
workspaces which are not supported in Microsoft Office Access 2007.
In DAO, when you open databases, they automatically exist within the default workspace which is the first
workspace in the Workspaces collection. You need to use the DBEngine.CreateWorkspace Method only to
create a second workspace which is seldom required.
Example 1: DAO WorkSpace Object & Workspaces Collection.
1. Create a new Workspace object, using the CreateWorkspace method, and append to the Workspaces
collection.
2. Access properties of all workspace objects (ie. default workspace and the newly created workspace).
Sub AccessDAO_CreateWorkspace_1()
'Create a new Workspace object, using the CreateWorkspace method, and append to the Workspaces
collection.
'Access properties of all workspace objects (ie. default workspace and the newly created workspace).
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'create a new Microsoft Jet Workspace, with the default type of dbUseJet:
Set wrkSpaceNew = DBEngine.CreateWorkspace("newWS", "admin", "", dbUseJet)
'return the number of workspace objects in the Workspaces collection (returns 2 - default & new workspace):
MsgBox DBEngine.Workspaces.count
'access properties of all workspace objects (ie. default workspace and the newly created workspace):
For Each wrkSpace In DBEngine.Workspaces
'workspace name (returns "#Default Workspace#" & "newWS"):
MsgBox "Workspace Name: " & wrkSpace.Name
'username property setting:
MsgBox wrkSpace.UserName
'properties of workspace object:
For Each prpWrkSpace In wrkSpace.Properties
MsgBox "Property Name: " & prpWrkSpace.Name
Next prpWrkSpace
Next wrkSpace
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
Dim strMyPath As String, strDBName As String, strDB As String, strDBNameNew As String, strDBNew As
String
Dim daoDB As DAO.Database, daoDBNew As DAO.Database, daoDBS As DAO.Database
Dim wrkSpaceNew As DAO.Workspace
Dim prpDB As DAO.Property
'---------------
'SET DATABASE NAMES (EXISTING & NEW):
'your data source with which to establish connection - ENTER the existing MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'CREATE A NEW MICROSOFT JET WORKSPACE:
'create a new Microsoft Jet Workspace, with the default type of dbUseJet:
Set wrkSpaceNew = DBEngine.CreateWorkspace("newWS", "admin", "", dbUseJet)
'---------------
'OPEN AN EXISTING DATABASE:
'If you open a database by specifying a workspace object, it will exist within the specified workspace:
Set daoDB = wrkSpaceNew.OpenDatabase(strDB, True)
'alternatively:
'Set daoDB = DBEngine.Workspaces("newWS").OpenDatabase(strDB, False)
'---------------
'CREATE A NEW DATABASE:
'If you create a database object without specifying a workspace, it will exist within the default workspace:
Set daoDBNew = DBEngine.CreateDatabase(strDBNew, dbLangGeneral)
'alternatively, to create a new database and open in the new Workspace object:
'Set daoDBNew = wrkSpaceNew.CreateDatabase(strDBNew, dbLangGeneral)
'---------------
'ACCESS DATABASES IN EACH WORKSPACE (DEFAULT AND NEW WORKSPACE):
'---------------
'close the objects:
daoDB.Close
daoDBNew.Close
wrkSpaceNew.Close
End Sub
Return a Reference to the Current Database - CurrentDb Method
Use the CurrentDb Method to return a reference to the database which is currently open in the Microsoft
Access window, from vba code. The method returns a database object, without the need to specfy the database
name. You can use other DAO objects with the database object variable returned by this method. A reference
to the current database is provided by the first member of the Databases collection. The reference pointed to
the current database by using the syntax DBEngine(0)(0) can also be used but this syntax refers to the open
copy of the current database, whereas with the CurrentDb method you can create 'multiple database object
variables' referring to the current database because this method creates a new instance of the current database
making it amenable for multi users. However, it is much slower to use CurrentDb than using DBEngine(0)(0).
Note that another Database can be opened and worked upon simultaneously, using the OpenDatabase
method, while the current database is already open in the Microsoft Access window.
Example 3: CurrentDb Method - return a reference to the currently open database.
Sub AccessDAO_ReferCurrentDatabase_3()
'CurrentDb Method - return a reference to the currently open database.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'RETURN MULTIPLE INSTANCES OF THE DATABASE CURRENTLY OPEN IN THE MICROSOFT ACCESS
WINDOW:
MsgBox daoCDB1.Name
MsgBox daoCDB2.Name
'refer DAO TableDef Object in current database - you need to first assign the current database reference to an
object variable (ex. daoCDB2):
Dim daoTblDef As DAO.TableDef
Dim fld As DAO.Field
Set daoTblDef = daoCDB2.TableDefs("SalesManager")
For Each fld In daoTblDef.Fields
MsgBox fld.Name
Next fld
'----
'USE CurrentDb DIRECTLY WITH A RECORDSET OBJECT:
'CurrentDb can be used directly with a Recordset object, while in most other DAO objects you need to first
assign the current database reference to an object variable as above.
Set recSet = CurrentDb.OpenRecordset("SalesManager", dbOpenDynaset)
'---------------
'OPEN ANOTHER DATABASE USING THE OpenDatabase METHOD, TO WORK ON SIMULTANEOUSLY,
WHILE THE CURRENT DATABASE IS ALREADY OPEN IN THE MICROSOFT ACCESS WINDOW:
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
MsgBox daoDB.Name
'---------------
'close the objects:
recSet.Close
daoCDB1.Close
daoCDB2.Close
daoDB.Close
Image 4a
Sub AccessDAO_CreateTablesCreateFields_4a()
'Create a New Database;
'Create & Append Tables (ie. TableDef objects);
'Create & Append Fields;
'Enumerate Tables in the Database and their Properties;
'Enumerate Fields in a Table;
'Delete Fields & Tables;
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
Dim strMyPath As String, strDBName As String, strDB As String
Dim daoDB As DAO.Database
Dim daoTD As DAO.TableDef, daoTD1 As DAO.TableDef, daoTD2 As DAO.TableDef
Dim daoFld As DAO.Field
Dim daoPrp As DAO.Property
'---------------
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'name of the new MS Access Database being created:
strDBName = "SalesReportNew.accdb"
'set the string variable to the new Database:
strDB = strMyPath & "\" & strDBName
'---------------
'CREATE A NEW MS ACCESS DATATABASE, TABLES AND FIELDS:
'Refer Image 4a to view Tables & Fields (in "SalesManager" Table) of the new Database
("SalesReportNew.accdb") after running below code, before deleteing any table or field.
'Create a New Database: If you create a database object without specifying a workspace, it will exist within the
default workspace:
Set daoDB = DBEngine.CreateDatabase(strDB, dbLangGeneral)
'Before you append the TableDef object to the TableDefs collection, you will create Fields and append them to
the new TableDef object (Table named "Performance") created above:
With daoTD2
.Fields.Append .CreateField("FirstName", dbText)
End With
'Save/Append the tables "SalesManager" & "Performance" to the TableDefs collection:
daoDB.TableDefs.Append daoTD1
daoDB.TableDefs.Append daoTD2
'---------------
'ENUMERATE DATABASE TABLES AND PROPERTIES:
'---------------
'ENUMERATE TABLE FIELDS:
'---------------
'close the objects:
daoDB.Close
Image 4b
Sub AccessDAO_AddRecordsEnterData_4b()
'Add new records to a table using the AddNew method;
'edit records using the Edit method;
'Use the Recordset.Bookmark Property to identify the current record;
'Use Recordset.LastModified Property pointing to the most recent added / modified record.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'Refer Image 4b after running below code which adds & edits records in the database file created in example 4a
above (note that the field "SurName" of "SalesManager" Table has not been deleted).
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReportNew.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'If you open a database object without specifying a workspace, it will exist within the default workspace. First
assign the database reference to an object variable:
Set daoDB = DBEngine.OpenDatabase(strDB)
'----------------
'add new records to a table, using the AddNew method (of the Recordset object):
With recSet
.AddNew
'you need not enter a value for the auto-incrementing field of "EmployeeId"; the start value is 1. In DAO you
cannot set the Seed of the auto-number, however you can start at a specific value in a new table by entering
the specific value for the first record of an AutoNumber field and subsequent records will increment from this
specific start value.
.Fields("EmployeeId") = 55
.Fields("FirstName") = "Lisa"
.Fields("SurName") = "Randall"
'enter a date/time value between # and #, or within double-quotes:
.Fields("JoinDate") = "08/11/2012"
.Fields("Sales") = "22456"
.Fields("NewJoinee?") = True
'for a hyperlink field, use both # and double-quotes:
.Fields("WebProfile") = "#http://www.google.com#"
'will save only after Update method is run:
.Update
.AddNew
'note that "JoinDate" field is omitted, hence its default value will be entered
.Fields("FirstName") = "Tracy" & " " & "Von"
.Fields("SurName") = "Murray"
.Fields("Sales") = "41098"
.Fields("NewJoinee?") = False
.Fields("WebProfile") = "#http://www.yahoo.com#"
.Update
'second record - save position of current record:
.Bookmark = .LastModified
recBookMark = .Bookmark
.AddNew
.Fields("FirstName") = "John"
.Fields("SurName") = "Mason"
.Fields("JoinDate") = #9/2/2012#
.Fields("Sales") = "31478"
.Fields("NewJoinee?") = True
.Fields("WebProfile") = "#http://www.msn.com#"
.Update
'In DAO, after the Update, the current record will be the record which had focus before the AddNew. Using the
LastModified property (for a DAO recordset - it does not work with an ADO recordset) returns a Bookmark
pointing to the most recent added / modified record. This makes the new record as the current record.
.Bookmark = .LastModified
End With
'returns "John"
MsgBox recSet.Fields("FirstName")
'edit the new record, using the Edit method (of the Recordset object):
With recSet
'Recordset.Edit Method is valid for a DAO recordset, it does not work with an ADO recordset:
.Edit
.Fields("FirstName") = "Julia"
.Fields("SurName") = "Willis"
'will save only after Update method is run:
.Update
End With
'returns "Julia"
MsgBox recSet.Fields("FirstName")
'return the second record whose position was saved:
recSet.Bookmark = recBookMark
'returns "Tracy Von"
MsgBox recSet.Fields("FirstName")
'---------------
'close the objects:
daoDB.Close
End Sub
Example 5a: Open Recordset, Enumerate Recordset, Recordset Properties, Navigate
through Records.
1. OpenRecordset method of the Database object - Open Recordset based on a Table; Open Recordset based
on a SQL statement.
2. OpenRecordset method of the TableDef object - Open Recordset based on a Table.
3. Enumerate the Recordset; List all valid properties of Recordset.
4. Use the MoveFirst and MoveNext methods to navigate through records, together with EOF Property.
Sub AccessDAO_OpenRecordsetMoveThruRecords_5a()
'OPEN RECORDSET; ENUMERATE RECORDSET; RECORDSET PROPERTIES; NAVIGATE THROUGH
RECORDS:
'OpenRecordset method of the Database object - Open Recordset based on a Table; Open Recordset based
on a SQL statement.
'OpenRecordset method of the TableDef object - Open Recordset based on a Table.
'Enumerate the Recordset; List all valid properties of Recordset.
'Use the MoveFirst and MoveNext methods to navigate through records, together with EOF Property.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'If you open a database object without specifying a workspace, it will exist within the default workspace. First
assign the database reference to an object variable:
Set daoDB = DBEngine.OpenDatabase(strDB)
'---------------
'OpenRecordset METHOD OF THE DATABASE OBJECT - OPEN RECORDSET BASED ON A TABLE:
'return the first field (name & value) of each record of the Recordset:
'while moving forward within a recordset, use EOF so as not to cross the last record. EOF Property indicates
that the current record position is after the last record in the set of records.
Do While Not recSet.EOF
MsgBox recSet.Fields(0).Name & " - " & recSet.Fields(0).Value
'MoveNext method moves the current record one position forward.
recSet.MoveNext
Loop
recSet.Close
Set recSet = Nothing
'-----
'OpenRecordset METHOD OF THE DATABASE OBJECT - OPEN RECORDSET BASED ON AN SQL
STATEMENT:
recSet.Close
Set recSet = Nothing
'-----
'OpenRecordset METHOD OF THE TableDef OBJECT - OPEN RECORDSET BASED ON A TABLE:
'refer to a TableDef object by its name: reference the table named SalesManager
Set daoTblDef = daoDB.TableDefs("SalesManager")
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Example 5b: Count the number of Records in a Recordset - DAO Recordset.RecordCount
Property.
Refer Image 5 as mentioned in the code.
Image 5
Sub AccessDAO_RecordCount_5b()
'Count the number of Records in a Recordset - DAO Recordset.RecordCount Property
'refer Image 5 to view the SalesManager Table in MS Access file "SalesReport.accdb", on which RecordCount
is done in this code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'RecordCount in a TableDef object:
Set daoTblDef = daoDB.TableDefs("SalesManager")
'returns 5, refer Image 5:
MsgBox "RecordsCount in a TableDef Object: " & daoTblDef.RecordCount
'-----
'RecordCount in a Table-type recordset:
Set recSet = daoDB.OpenRecordset("SalesManager", dbOpenTable)
'returns 5, refer Image 5:
MsgBox "RecordsCount in Table-type recordset: " & recSet.RecordCount
recSet.Close
Set recSet = Nothing
'-----
'RecordCount in a Dynaset-Type recordset:
strSQL = "SELECT * FROM SalesManager WHERE EmployeeId > 18"
Set qryD = daoDB.CreateQueryDef("sqlQuery", strSQL)
daoDB.QueryDefs.Delete ("sqlQuery")
recSet.Close
Set recSet = Nothing
'-----
'RecordCount in a Snapshot-type recordset:
Set recSet = daoDB.OpenRecordset("SalesManager", dbOpenSnapshot)
'returns 1, refer Image 5:
MsgBox "RecordsCount in Snapshot-type recordset BEFORE MoveLast: " & recSet.RecordCount
recSet.MoveLast
'returns 5, refer Image 5:
MsgBox "RecordsCount in Snapshot-type recordset AFTER MoveLast: " & recSet.RecordCount
recSet.Close
Set recSet = Nothing
'-----
'RecordCount in a Forward-only-type recordset:
Set recSet = daoDB.OpenRecordset("SalesManager", dbOpenForwardOnly)
'returns 1, refer Image 5:
MsgBox "RecordsCount in Forward-only-type recordset BEFORE MoveNext: " & recSet.RecordCount
recSet.MoveNext
'returns 2, refer Image 5:
MsgBox "RecordsCount in Forward-only-type recordset AFTER first MoveNext: " & recSet.RecordCount
recSet.MoveNext
'returns 3, refer Image 5:
MsgBox "RecordsCount in Forward-only-type recordset AFTER second MoveNext: " & recSet.RecordCount
'-----
'close the objects:
recSet.Close
daoDB.Close
End Sub
Example 6: Find Method (FindFirst & FindNext) in a Dynaset or Snapshot-type recordset;
Edit / Delete Records.
Refer Images 6a, 6b & 6c as mentioned in the code.
1. Locate records matching specified criteria using the FindFirst and FindNext methods in a dynaset or
snapshot-type recordset;
2. Edit a record using the Edit method;
3. Delete a record using the Delete method.
Image 6a
Image 6b
Image 6c
Sub AccessDAO_FindMethod_EditDeleteRecords_6()
'Locate records matching specified criteria using the FindFirst and FindNext methods in a dynaset or snapshot-
type recordset;
'Edit a record using the Edit method;
'Delete a record using the Delete method;
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'refer Image 6a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'----------------
'USE FindFirst AND FindNext METHODS TO LOCATE ALL RECORDS THAT MATCH A SPECIFIED
CRITERIA:
'--------------------
'LOCATE RECORD TO EDIT, USING THE FindFirst METHOD:
'refer Image 6b after running below code:
'--------------------
'FIND RECORD WHICH YOU WANT TO DELETE:
'refer Image 6c after running below code:
recSet.FindFirst "EmployeeId=56"
'modifying a DAO recordset - delete a record in a table, using the Delete method (of the Recordset object):
'record with EmployeeId 56 is deleted, refer Image 6c:
If recSet.NoMatch = False Then
recSet.Delete
Else
MsgBox "Record Not Found"
End If
'no current record after the Delete method is used, hence go to First Record:
recSet.MoveFirst
'returns Tracy, refer Image 6c:
MsgBox recSet.Fields("FirstName")
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Example 7: Use the DAO Recordset.Filter Property to Filter Records (applicable to dynaset–
type, snapshot–type, or forward–only–type Recordsets).
Refer Images 7a & 7b, as mentioned in the code.
Image 7a
Image 7b
Sub AccessDAO_RecordsetFilter_7()
'Filter Records: Use the DAO Recordset.Filter Property to determine inclusion of records in a Recordset opened
thereafter. A Filter can be applied to dynaset–type, snapshot–type, or forward–only–type Recordsets.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)
recSet.Close
Set recSet = Nothing
'---------------
'create a filtered Recordset (dynaset–type) with an SQL statement, returning records from SalesManager Table
whose Employee Id is between 15 and 56, returning/sorting them in the order of JoinDate:
Set recSet = daoDB.OpenRecordset("SELECT * FROM SalesManager WHERE EmployeeId BETWEEN 15
AND 56 ORDER BY JoinDate")
'refilter the recordset using the Filter property, returning records whose JoinDate is post "01/01/2011" and mark
them as NewJoinee:
recSet.Filter = "JoinDate BETWEEN #01/01/2011# AND Now"
'create another filtered Recordset (dynaset–type), using the DAO Recordset.OpenRecordset Method:
Set recSetF = recSet.OpenRecordset
'return the EmployeeId & JoinDate fields of each record in the filtered Recordset:
'refer Image 7b to view the SalesManager Table, after running below code.
Do While Not recSetF.EOF
MsgBox recSetF.Fields("EmployeeId") & ", " & recSetF.Fields("JoinDate")
'set values of filtered records in NewJoinee? field to True:
recSetF.Edit
recSetF.Fields("NewJoinee?").Value = True
recSetF.Update
recSetF.MoveNext
Loop
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Microsoft Access DAO Object Model: Create an Index, Create Relationship
between Fields, Create and Exceute a Query
Microsoft Access DAO Object Model: Create an Index, Create Relationship between Fields,
Create and Exceute a Query
Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases
from Excel using VBA.
Part 2 of 3
Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases from Excel
using VBA:
1. Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model.
2. Microsoft Access DAO Object Model: Create an Index, Create Relationship between Fields, Create
and Execute a Query.
3. Microsoft Access DAO Object Model: Import or Export Data from Access to Excel.
----------------
Also Read:
Microsoft Access: ActiveX Data Objects (ADO), Connect with Access Databases from Excel using VBA.
---------------------------------------------------------------------------------------------------------
Contents:
Create an Index using DAO
Create Relationship between Fields of Database Tables, using DAO
Create and Exceute a Query, including Action & Parameter Query, using DAO
---------------------------------------------------------------------------------------------------------
An Index specifies the order of accessing records and can disallow duplicate values in a field. Index enables
quick search of records in a table, and it can be created on one or multiple table columns. Key is a means to
identify records in a table, wherein data can be related by using one or more columns as key columns. You can
relate multiple tables by creating a relationship between key fields of each. SQL statements are referred to
as queries. You may create a Recordset based on a stored query or a parameter query.
Create an Index using DAO
An Index specifies the order of accessing records and can disallow duplicate values in a field. Index enables
quick search of records in a table, and it can be created on one or multiple table columns. An index speedily
points directly to the row containing a given value in the indexed column(s), instead of searching every row
inserted in a random order in the table. Key is a means to identify records in a table, wherein data can be
related by using one or more columns as key columns. Primary key can be specified as one or more columns
having unique values, and cannot be Null. There can be only one Primary key in a Table.
Steps to create an Index in a database table:
Step 1: Create an Index object, using the DAO TableDef.CreateIndex Method.
Step 2: Set Index properties viz. set index name, set as primary key index, allow / disallow null value in index
field, and so on.
Step 3: Define Index Field(s) - Create Field object(s) for the Index object (using its CreateField method) and
Append these to the fields collection of the Index object.
Step 4: Append the Index object to the TableDef's Indexes collection (using the Indexes.Append Method).
Create an Index object
Use the TableDef.CreateIndex Method to Create an Index in a Database Table. Syntax:
TableDefObject.CreateIndex(Name). The Name argument (optional) is a string value specifying the name
(maximum length of 64 characters) of the new Index. If you do not specify the Name in the CreateIndex method,
you can set it later by assigning the name to the Index object before appending the new Index object to a
collection.
DAO Indexes Collection
Indexes Collection refers to all Index objects of a Table.
DAO Indexes Collection Methods and Properties:
DAO Indexes.Append Method. Use the Append method to add a new index to the Indexes collection:
TableDefObject.Indexes.Append(IndexObject).
DAO Indexes.Delete Method. To Delete an Index object, use the Delete method:
TableDefObject.Indexes.Delete(IndexName).
DAO Indexes.Refresh Method: The Refresh method is particularly required to be used in a multi-user
environment wherein different users might be making changes in the database, in which case only those
objects are contained when you have referred to the collection initially without reflecting any subsequent
changes made by other users, and the collection will get updated only on using the Refresh method. To refresh
the indexes collection: TableDefObject.Indexes.Refresh.
DAO Indexes.Count Property: The Count property of the Indexes collection determines the number of Index
objects in the collection. When there are no objects in the collection, the Count property value will be 0.
DAO Index Object
An Index specifies the order of accessing records and can disallow duplicate values in a field. Index enables
quick search of records in a table, and it can be created on one or multiple table columns.
DAO Index Object Methods and Properties:
Some methods & properties of an Index object are briefly discussed here.
DAO Index.CreateField Method
To create a new field for an Index object, use the Index.CreateField Method. Syntax:
IndexObject.CreateField(Name, Type, Size). All arguments are optional to specify. The Name argument
specifies a name for the new Field. The Type and Size arguments are not supported for an Index object, and
are ignored in this case. If the Name argument is not specified in the method, you can set the Name property
thereafter but before the Field is appended to the Fields collection of the Index object.
To delete a field from the Fields Collection, use the DAO Fields.Delete Method. Note that once an index
referencing a field has been created, that Field cannot be deleted from a Fields collection of a TableDef object.
DAO Index.Name Property
Use the Name property to set or return the name (a string value with maximum length of 64 characters) of an
Index object. The property is read/write before the Index object is appended to a collection and read-only after
appending. Syntax: IndexObject.Name.
DAO Index.Primary Property
Use the Index.Primary Property to determine whether the Index object is as a primary key index for a
database table. Use the Syntax IndexObject.Primary = True to set the Index object as a primary key index.
Default value is False. The Unique and Required properties are automatically set to True for a primary key
index. A primary key index will identify all records of a table uniquely in a predefined order. If an Index is not
primary, it is a secondary index (ie. when the Primary property of the Index is set to False). The Primary
property is read/write before the Index object is appended to the Indexes collection and read-only for an
appended Index object. Note that the Primary property is read/write also in the case when the Index object is
appended to the TableDef object which itself is not appended to the TableDefs collection.
DAO Index.Unique Property
Use the Index.Unique Property to determine whether values in an Index should be unique or not. Setting the
property to True will identify all records uniquely in the table. For a single-field index this means that all values
within the field should be unique, whereas for a multi-field index this means that though duplicate values are
allowed within a particular field but each set of values combined from all indexed fields should be
unique. Syntax: IndexObject .Unique. The property is read/write before the Index object is appended to a
collection and read-only after appending.
DAO Index.Required Property
The Index.Required Property determines whether an index field can accept null values. Setting the Required
Property to False will allow null values in the indexed field. Between an Index object and a Field object, set the
Required property for the Field object because its validation for the Field object precedes that of an Index
object. Default setting is False. Syntax: IndexObject.Required.
DAO Index.IgnoreNulls Property
Syntax: IndexObject.IgnoreNulls. This property is read/write before the Index object is appended to a
collection and read-only after appending. Default setting is False. The IgnoreNulls Property determines
whether a record having a null value in its index field will be included in the index (ie. will have an index entry or
not). The IgnoreNulls property and Required property are used together to determine an index entry for records
having null index values. When the Required property for an Index is False: (i) records are allowed to have a
null value in the Index field and if IgnoreNulls property is True, an index entry WILL NOT be added for the
record; and (ii) records are allowed to have a null value in the Index field and if IgnoreNulls property is False, an
index entry WILL be added for the record. When the Required property for an Index is True, records are NOT
allowed to have a null value in the Index field, and in this case the record with a non-null value in its Index field
will have an index entry. If you want to allow null values in the Index field and expect a large number of null
values therein, setting the IgnoreNulls property to True will reduce the storage space used by the Index. Refer
Example 8b which explains this property.
Index property of a Recordset Object: DAO Recordset.Index Property
Index is created for a database Table and appended to the Indexes collection of the underlying TableDef object.
An Index does not change the order in which records are actually stored in a base table, but only affects the
order in which they are returned or are accessed in a Recordset when it is opened or when a particular Index is
selected. For a table-type Recordset object you can set the order of the records only with an index which is
already defined for the underlying TableDef object. Use the Recordset.Index property in a table-type
Recordset object to set or return the name of the current Index object - Syntax: RecordsetObject.Index. Note
that you can use an SQL statement ORDER BY clause in a dynaset-type or snapshot-type or forward-only-type
Recordset to sort records in an order other than in a defined Index of a table.
Example 8a: Create Index Keys (Primary Index, Single-Field Index & Multi-Field Index) for
Fields in a Database.
Refer Images 8a, 8b, 8c & 8d as mentioned in the code.
Image 8a
Image 8b
Image 8c
Image 8d
Sub AccessDAO_CreateIndex_8a()
'create Index Keys (Primary Index, Single-Field Index & Multi-Field Index) for Fields in a database, using DAO
'refer Image 8a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'refer to a TableDef object by its name: reference the table named SalesManager
Set daoTblDef = daoDB.TableDefs("SalesManager")
'----------------
'Steps to create an Index:
'Step 1: Create an Index object, using the DAO TableDef.CreateIndex Method.
'Step 2: Define Index properties viz. set index name, set as primary key index, allow / disallow null value in
index field, and so on.
'Step 3: Define Index Field(s) - Create Field object(s) for the Index object (using its CreateField method) and
Append these to the fields collection of the Index object.
'Step 4: Append the Index object to the TableDef's Indexes collection.
'----------------
'CREATE A PRIMARY KEY INDEX:
'refer Image 8b showing the "SalesManager" Table where the Primary Index has been created on "EmployeeId"
column whose values appear in ascending order and the column cannot have duplicate values. The Unique and
Required properties are automatically set to True for a primary key index:
'----------------
'CREATE A SINGLE-FIELD INDEX WITH UNIQUE VALUES:
'refer Image 8c showing the "SalesManager" Table where the Index has been created on "Surname" column
whose values appear in ascending order and the column cannot have duplicate values.
'----------------
'CREATE A MULTI-FIELD INDEX:
'refer Image 8d showing the "SalesManager" Table where the Index has been created on 2 columns,
"FirstName" and "Surname", wherein values appear in ascending order based on both columns - note that "Jim
Davis" which was below "Jim Mason" originally now precedes it.
'---------------
'close the objects:
daoDB.Close
End Sub
Example 8b: When the Required property setting is False for an Index object, records with
Null value have an index entry depending on the Index.IgnoreNulls property setting.
Refer Images 8a & 8e as mentioned in the code.
Image 8e
Sub AccessDAO_CreateIndex_8b()
'When the Required property setting is False for an Index object: records with Null value have an index entry if
IgnoreNulls = False; records with Null value do NOT have an index entry if IgnoreNulls = True;
'refer Image 8a to view the existing SalesManager Table in MS Access file "SalesReport.accdb"; refer Image 8e
after running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport4.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'refer to a TableDef object by its name: reference the table named SalesManager
Set daoTblDef = daoDB.TableDefs("SalesManager")
'----------------
Set daoIndex = daoTblDef.CreateIndex
'define index properties:
With daoIndex
.Name = "iSurNm"
'determine if a record with null value in the index field will be included in the index:
.IgnoreNulls = False
.Unique = True
.Fields.Append .CreateField("Surname")
End With
daoTblDef.Indexes.Append daoIndex
With recSet
'add new record with a null value for the "Surname" index field:
.AddNew
.Fields("EmployeeId") = 55
.Fields("FirstName") = "Albert"
.Update
'set index for the recordset using the Recordset.Index Property:
.Index = daoIndex.Name
.MoveFirst
'refer Image 8e showing "SalesManager" table in which new record is added, which will be included in the
index depending on the IgnoreNulls property setting when the Required property setting is False (default).
'If IgnoreNulls = False, record with Null value has an index entry and messages returned are: Albert Null, Jim
Davis, Sam Green, David Kelly, Jim Mason, Tracy Murray.
'If IgnoreNulls = True, record with Null value does not have an index entry and messages returned are: Jim
Davis, Sam Green, David Kelly, Jim Mason, Tracy Murray.
Do While Not .EOF
If IsNull(.Fields("Surname")) Then
MsgBox "First Name: " & .Fields("FirstName") & ", " & "Surname: Null"
Else
MsgBox "First Name: " & .Fields("FirstName") & ", " & "Surname: " & .Fields("Surname")
End If
.MoveNext
Loop
End With
End Sub
Recordset.Seek Method
Use the Seek method for a table-type recordset, to locate a record meeting the criteria specified for the current
index. If the Seek method finds the record, the located record becomes the current record and the NoMatch
property is set to False. However if a record is not found, the current record is undefined and method sets the
NoMatch property to True. Syntax: RecordsetObject.Seek(ComparisonExpression, Key1, Key2, ... Key13).
Both the arguments of ComparisonExpression and Keys are required to be specified.
The ComparisonExpression can be any of the 5 expressions: >, =, >=, <, <=. The Key argument is a value
evaluated against the current Index field and you can specify a maximum of 13 keys, wherein Key1 must be of
the same data type as that of the current index field.
Note that a current Index must be set (using the Index property) for the Recordset before using the Seek
method, and in case the index field is not unique (ie. the field has duplicate values) then the first record which
satisfies the criteria is located. For comparison expressions of greater than (>), equal (=), or greater than or
equal (>=), the search is started at the beginning of the index and moves forward. For comparison expressions
of less than (<) or less than or equal (<=), the search is started at the index end and moves backward and if the
index end has duplicate entries then search starts randomly from any of these duplicate entries and moves
backward. As mentioned earlier, to search through Dynaset-type or Snapshot-type recordsets, you will need to
use the Find method (which is slower the Seek method) which is supported by these recordsets.
Example 9: Use the Seek method for a table-type recordset, to locate a record.
Sub AccessDAO_SeekMethod_9()
'Use the Seek method for a table-type recordset, to locate a record meeting the criteria specified for the current
index.
'If the Seek method finds the record, the located record becomes the current record and the NoMatch property
is set to False. However if a record is not found, the current record is undefined and method sets the NoMatch
property to True.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'refer to a TableDef object by its name: reference the table named SalesManager
Set daoTblDef = daoDB.TableDefs("SalesManager")
'----------------
'CREATE A PRIMARY KEY INDEX:
Set daoIndex = daoTblDef.CreateIndex("piEmpId")
With daoIndex
.Primary = True
.Required = True
.Fields.Append .CreateField("EmployeeId")
End With
daoTblDef.Indexes.Append daoIndex
'----------------
With recSet
'specify the index name wherein to search with the Seek method - set index for the recordset using the
Recordset.Index Property:
.Index = "piEmpId"
'save position of current record to which you might want to return later:
recBookMark = .Bookmark
MsgBox recSet.Fields("FirstName")
'specify search value:
intSeek = InputBox("Enter EmployeeID to locate")
'run the Seek meth0d:
.Seek "=", intSeek
'check whether matching record found or not by the Seek method:
If .NoMatch Then
'return the record whose position was saved, if no match is found by the Seek method:
.Bookmark = recBookMark
MsgBox "Not found EmployeeID: " & intSeek & ", reverted to initial record: " & recSet.Fields("FirstName")
Else
'return the matching record found by the Seek method:
MsgBox "Found EmployeeID: " & intSeek & ", whose First Name is: " & recSet.Fields("FirstName")
End If
'close recordset:
.Close
End With
'---------------
'delete index by reference to its name:
daoTblDef.Indexes.Delete "piEmpId"
'---------------
'close the objects:
daoDB.Close
End Sub
Create Relationship between Fields of Database Tables, using DAO
An Index specifies the order of accessing records and can disallow duplicate values in a field. Index enables
quick search of records in a table, and it can be created on one or multiple table columns. Key is a means to
identify records in a table, wherein data can be related by using one or more columns as key columns. Primary
key can be specified as one or more columns having unique values, and cannot be Null. There can be only one
Primary key in a Table.
A relational database has multiple tables, each table comprising of columns (fields) and rows wherein data can
be grouped using common attributes, and from which data can be easily retrieved. The multiple tables relate to
and work with each other through certain key fields (like unique "ID Nos") viz. a separate table is created for
vendor-details and another table for purchase-orders wherein vendor details are not repeated each time a
purchase order is made and they are related with each other through a unique "Vendor ID" column which is
present in both tables.
You can relate multiple tables (we consider 2 tables here) by creating a relationship between key fields (usually
the 'primary key' fields) of each. We refer one table as the 'primary table', for which a unique index is required
for the key field so that this key field contains unique values. The other table is referred as 'foreign table' and its
key field as the 'foreign key'. The unique index field of the primary table is related to the 'foreign key'. Note that
though it is not required that the foreign key field contain unique values, it is preferable to do so otherwise
relating multiple options from the foreign key to a single/unique value in the key field of the primary table might
become meaningless.
Relation Object
A Relation object shows the relationship between fields in tables of a database. Use a Relation object to relate
tables by creating a relationship between fields or return existing relationships in a database. A new Relation
object is created using the Database.CreateRelation Method. Within the Relations collection of a Database,
you can refer a Relation object by its ordinal position or Name property - to reference a Relation named
"RelationName", which is the first relation object in the database, you can use any of the following:-
DatabaseObject.Relations("RelationName") or DatabaseObject![RelationName] or
DatabaseObject.Relations(0).
Steps to Create a Relation between Key Fields of Tables:
Step 1: Reference the Primary table and Foreign table - assign to object variables (TableDef).
Step 2: Create Index for the Primary table - the Indexed field will be part of the relationship.
Step 3: Create a new Relation object (using the Database.CreateRelation Method), specifying names of the
Primary & Foreign tables to be related, and also specifying the Attributes for the relationship type.
Step 4: Create a new Field object (using the Relation.CreateField Method) for the Relation object; specify Field
names of the Primary & Foreign table which will be part of the relationship; and append the new Field object to
the Fields collection of the Relation object.
Step 5: Append the new Relation object to the Relations collection of the Database.
Image 10a
Image 10b
Image 10c
Sub AccessDAO_TablesCreateRelation_10()
'Create a Relation between Two Tables, using DAO - relationship between fields in two TableDef (or QueryDef)
objects using the Database.CreateRelation Method.
'refer Image 10a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'refer Image 10b to view the existing Performance Table in MS Access file "SalesReport.accdb".
'refer Image 10c to view the SalesManager Table, after Creating Relation by running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'----------------
'Steps to Create a Relation between Key Fields of Tables:
'Step 1: Reference the Primary table and Foreign table - assign to object variables (TableDef).
'Step 2: Create Index for the Primary table - the Indexed field will be part of the relationship.
'Step 3: Create a new Relation object (using the Database.CreateRelation Method), specifying names of the
Primary & Foreign tables to be related, and also specifying the Attributes for the relationship type.
'Step 4: Create a new Field object (using the Relation.CreateField Method) for the Relation object; specify Field
names of the Primary & Foreign table which will be part of the relationship; and append the new Field object to
the Fields collection of the Relation object.
'Step 5: Append the new Relation object to the Relations collection of the Database.
'Create Index for the primary table "SalesManager". The indexed field will create relationship with the foreign
table's field:
Set daoIndx = tblDefSM.CreateIndex("indxEmpId")
With daoIndx
.Required = True
.Unique = True
.Fields.Append .CreateField("EmployeeId")
End With
tblDefSM.Indexes.Append daoIndx
'Create Relation object named relSalesPerf, specifying names of the primary & foreign tables to be related, and
also specifying the attributes for the relationship type.
Set daoRel = daoDB.CreateRelation("relSalesPerf", tblDefSM.Name, tblDefP.Name,
dbRelationUpdateCascade)
'create field object for the Relation object daoRel and append to its fields collection.
With daoRel
'specify field name of the primary table which has been indexed and will be a part of the relationship:
Set daoFld = .CreateField("EmployeeId")
'specify field name of the foreign table which will be a part of the relationship:
daoFld.ForeignName = "EmployeeId"
'Append the new field object to fields collection of the relation object:
daoRel.Fields.Append daoFld
End With
'append the new relation object daoRel to the Relations collection of the Database.
daoDB.Relations.Append daoRel
'delete relation:
'daoDB.Relations.Delete "relSalesPerf"
'delete Index:
'tblDefSM.Indexes.Delete "indxEmpId"
'---------------
'close the objects:
daoDB.Close
End Sub
Create and Exceute a Query, including Action & Parameter Query, using DAO
SQL statements are referred to as queries. A QueryDef object is a predefined query which is defined, saved
and stored in a Microsoft Access database for later use. The CreateQueryDef method is used to create a new
QueryDef object - Syntax of DAO Database.CreateQueryDef
Method: DatabaseObject.CreateQueryDef(QueryName, SQLText). Both QueryName & SQLText arguments
are Optional. This method automatically appends the QueryDef object to the QueryDefs collection if a valid
name is specified. A temporary QueryDef object which is not automatically appended to the collection, can be
created by using a zero-length string ("") for the QueryName argument. The SQLText argument specifies the
SQL statement.
If the QueryName and SQLText are not specified while creating the QueryDef object, these can be set later
using the object's Name & SQL properties - DAO QueryDef.Name Property & DAO QueryDef.SQL Property.
The Name property sets or returns the name of the QueryDef object, which cannot exceed 64 characters. The
SQL Property of the QueryDef object sets or returns the SQL statement by which a query is defined for the
QueryDef object. To delete the QueryDef object from a QueryDefs collection, use the QueryDefs.Delete
Method, Syntax: QueryDefs.Delete(Name).
To create a Recordset based on a stored query or a parameter query, use the DAO QueryDef.OpenRecordset
Method, Syntax: QueryDefObject.OpenRecordset(Type, Options, LockEdit). In this method you first get a
reference to the QueryDef object and then use the Set operator to return the recordset. Refer Example 11b in
which this method is used.
Example 11a: Create and Save a Query (QueryDef object).
Refer Image 11 as mentioned in the code.
Image 11
Sub AccessDAO_CreateSaveQuery_11a()
'create and save a query (QueryDef object).
'refer Image 11 which shows the SalesManager Table in MS Access file "SalesReport.accdb", and the query
"sqlQuery" that is created after running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'If you open a database object without specifying a workspace, it will exist within the default workspace. First
assign the database reference to an object variable:
Set daoDB = DBEngine.OpenDatabase(strDB)
'Specify QueryName and SQLText while creating the QueryDef object. The QueryDef object is automatically
appended to the QueryDefs collection.
Set qryD = daoDB.CreateQueryDef("sqlQuery", strSQL)
'---------------
'close the objects:
daoDB.Close
End Sub
Example 11b: Open Recordset based on a saved Query; Delete the QueryDef object.
Refer Image 11 as mentioned in the code.
Sub AccessDAO_OpenRecordSetSavedQuery_11b()
'Open Recordset based on a saved Query; return the first two fields of each record; delete the QueryDef object.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'Assign the database reference to an object variable:
Set daoDB = DBEngine.OpenDatabase(strDB)
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Example 12a: Create and Save a QueryDef object, with a Parameter Query.
Refer Image 12 as mentioned in the code.
Image 12
Sub AccessDAO_CreateParameterQuery_12a()
'create and save a QueryDef object, with a parameter query.
'refer Image 12 which shows the SalesManager Table in MS Access file "SalesReport.accdb", and the
parameter query "ParamQuery" that is created after running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)
'A parameter query is one in which the user is prompted to enter some information, such as selection criteria for
records or a field value to be inserted.
'SQL Parameterized query, is constructed with parameters, and assigned to the variable (strSQL).
strSQL = "PARAMETERS startDate DateTime, endDate DateTime; SELECT * FROM SalesManager WHERE
JoinDate between startDate and endDate"
'Create a QueryDef object, with the parameter query name "ParamQuery". The QueryDef object is automatically
appended to the QueryDefs collection.
Set qryD = daoDB.CreateQueryDef("ParamQuery")
'Because the SQLText was not specified while creating the QueryDef object, it is being set later using the
object's property:
qryD.Sql = strSQL
'alternatively, specify QueryName and SQLText while creating the QueryDef object:
'Set qryD = daoDB.CreateQueryDef("ParamQuery", strSQL)
'---------------
'close the objects:
daoDB.Close
End Sub
Example 12b: Open Recordset based on a saved Parameter Query; Delete the QueryDef
object.
Refer Image 12 as mentioned in the code.
Sub AccessDAO_OpenRecordSetParameterQuery_12b()
'Open Recordset based on a saved parameter Query; return the first two fields of each record; delete the
QueryDef object.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Run an Action Query or Execute SQL Statement
Image 13b
Sub AccessDAO_ExecuteActionQuery_13()
'Use the DAO Execute Method to run an action query, from a QueryDef object or a Database object.
'refer Image 13a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'refer Image 13b to view the SalesManager Table, after running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'SQL statement assigned to the variable (strSQL). The sql will change the FirstName from John to Johnny in the
SalesManager table.
strSQL = "UPDATE SalesManager SET FirstName = 'Johnny' WHERE FirstName = 'John'"
'Specify QueryName and SQLText while creating the QueryDef object. The QueryDef object is automatically
appended to the QueryDefs collection.
Set qryD = daoDB.CreateQueryDef("sqlQuery", strSQL)
MsgBox "query created"
'run an action query using the Database.Execute Method:
daoDB.Execute "sqlQuery"
'alternate code to run the action query:
'qryD.Execute
MsgBox "query executed"
'----
'set recordset:
Set recSet = daoDB.OpenRecordset("SalesManager")
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Example 14: Use the DAO Database.Execute Method to execute an SQL statement, from a
Database object.
Refer Images 13a & 14, as mentioned in the code.
Image 14
Sub AccessDAO_ExecuteSqlStatement_14()
'Use the DAO Database.Execute Method to execute an SQL statement, from a Database object.
'refer Image 13a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'refer Image 14 to view the SalesManager Table, after running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'Execute an SQL Statement (action sql) using the Database.Execute Method:
'The sql statement will change the FirstName from John to Johnny in the SalesManager table.
daoDB.Execute "UPDATE SalesManager SET FirstName = 'Johnny' WHERE FirstName = 'John'"
MsgBox "sql executed"
'----
'set recordset:
Set recSet = daoDB.OpenRecordset("SalesManager")
'---------------
'close the objects:
recSet.Close
daoDB.Close
End Sub
Example 15: Use the DAO QueryDef.Execute Method to run a Parameter Action Query, from
a QueryDef object.
Refer Images 13a & 15, as mentioned in the code.
Image 15
Sub AccessDAO_ExecuteParameterQuery_15()
'Use the DAO QueryDef.Execute Method to run a parameter action query, from a QueryDef object.
'refer Image 13a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'refer Image 15 to view the SalesManager Table, after running below code.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
'---------------
'assign the database reference to an object variable:
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)
'A parameter query is one in which the user is prompted to enter some information, such as selection criteria for
records or a field value to be inserted.
'SQL Parameterized query, is constructed with parameters, and assigned to the variable (strSQL).
strSQL = "PARAMETERS startDate DateTime, endDate DateTime; DELETE * FROM SalesManager WHERE
JoinDate between startDate and endDate"
'Create a QueryDef object, with the parameter query name "ParamQuery". The QueryDef object is automatically
appended to the QueryDefs collection.
Set qryD = daoDB.CreateQueryDef("ParamQuery", strSQL)
MsgBox "query created"
'enter parameters for the parameter query and run query using the Execute Method:
qryD.Parameters("[startDate]") = "01/01/2009"
qryD.Parameters("[endDate]") = "12/31/2010"
qryD.Execute
MsgBox "query executed"
End Sub
Microsoft Access DAO Object Model: Import or Export Data from Access to
Excel
Microsoft Access DAO Object Model: Import or Export Data from Access to Excel
Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases
from Excel using VBA.
Part 3 of 3
Microsoft Access: Data Access Objects Library (DAO), Connect with Access Databases from Excel
using VBA.
1. Connecting to Microsoft Access Database from Excel VBA, using DAO Object Model.
2. Microsoft Access DAO Object Model: Create an Index, Create Relationship between Fields, Create and
Execute a Query.
3. Microsoft Access DAO Object Model: Import or Export Data from Access to Excel.
-----------------
Also Read:
Microsoft Access: ActiveX Data Objects (ADO), Connect with Access Databases from Excel using VBA.
-------------------------------------------------------------------------------------------------
Contents:
Using Automation (DAO) to Copy Data from Microsoft Access to Excel
Import data from an Access Database Table to an Excel worksheet (your host application)
Export data from Excel worksheet (your host application) to an Access Database Table
-------------------------------------------------------------------------------------------------
Using Automation (DAO) to Copy Data from Microsoft Access to Excel: In this section we show, with the
help of practical examples, how to connect to Access Database from Excel (your host application) using DAO
to: (i) import or retrieve data from an Access database to Excel worksheet; and (ii) Export data from Excel
worksheet to an Access Database Table.
Range.CopyFromRecordset Method: This method is commonly used to copy records (valid for both ADO or
DAO Recordset objects) from an Aceess Table to an Excel worksheet. Syntax:
Range.CopyFromRecordset(Data, MaxRows, MaxColumns).
Range is the worksheet range to which the records are copied, starting at its upper-left corner. Data is the
Recordset (ie. set of records) in the Access database to be copied and the current row in the Recordset is the
starting record from where copying begins. MaxRows and MaxColumns refer to the maximum numbers of
rows (ie. records) and fields respectively to be copied and omitting these arguments will indicate that all rows
and fields are copied. Data is mandatory to specify while other arguments of MaxRows and MaxColumns are
optional.
Example 16: Import data from an Access Database Table to an Excel worksheet (your host
application).
Refer Images 16a, 16b, 16c, 16d & 16e as mentioned in the code.
Image 16a
Image 16b
Image 16c
Image 16d
Image 16e
Sub AccessDAO_ImportFromAccessToExcel_16()
'Using DAO to Import data from an Access Database Table to an Excel worksheet (your host application).
'refer Image 16a to view the existing SalesManager Table in MS Access file "SalesReport.accdb".
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'--------------
Dim strMyPath As String, strDBName As String, strDB As String
Dim i As Long, n As Long, lLastRow As Long, lFieldCount As Long
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
Dim ws As Worksheet
'set the worksheet:
Set ws = ActiveWorkbook.Sheets("Sheet8")
'--------------
'COPY RECORDS FROM ALL FIELDS USING CopyFromRecordset:
'refer Image 16b to view records copied to Excel worksheet
For i = 0 To lFieldCount - 1
'copy column names in first row of the worksheet:
rng.Offset(0, i).Value = recSet.Fields(i).Name
Next i
'copy record values starting from second row of the worksheet:
rng.Offset(1, 0).CopyFromRecordset recSet
'to copy 4 rows and 3 columns of the recordset to excel worksheet:
'rng.Offset(1, 0).CopyFromRecordset Data:=recSet, MaxRows:=4, MaxColumns:=3
'--------------
'COPY RECORDS FROM SELECTED FIELDS USING CopyFromRecordset:
'refer Image 16c to view records copied to Excel worksheet
'copy records from the selected fields (EmployeeId, FirstName & JoinDate):
strSQL = "SELECT EmployeeId, FirstName, JoinDate FROM SalesManager WHERE EmployeeId > 15"
'Open a dynaset-type recordset based on a SQL statement:
Set recSet = daoDB.OpenRecordset(strSQL, dbOpenDynaset)
For i = 0 To lFieldCount - 1
'copy column names in first row of the worksheet:
rng.Offset(0, i).Value = recSet.Fields(i).Name
Next i
recSet.Close
Set recSet = Nothing
'--------------
'COPY RECORDS FROM ALL FIELDS OF A RECORDSET:
'refer Image 16d to view records copied to Excel worksheet
For i = 0 To lFieldCount - 1
'copy column names in first row of the worksheet:
rng.Offset(0, i).Value = recSet.Fields(i).Name
recSet.MoveFirst
'copy record values starting from second row of the worksheet:
n=1
Do While Not recSet.EOF
rng.Offset(n, i).Value = recSet.Fields(i).Value
recSet.MoveNext
n=n+1
Loop
Next i
recSet.Close
Set recSet = Nothing
'--------------
'COPY RECORDS FROM SELECTED FIELDS OF A RECORDSET:
'refer Image 16e to view records copied to Excel worksheet
For i = 0 To lFieldCount - 1
'copy column names in first row of the worksheet:
rng.Offset(0, i).Value = recSet.Fields(i).Name
recSet.MoveFirst
'copy record values starting from second row of the worksheet:
n=1
Do While Not recSet.EOF
rng.Offset(n, i).Value = recSet.Fields(i).Value
recSet.MoveNext
n=n+1
Loop
Next i
recSet.Close
'--------------
'close the objects:
daoDB.Close
End Sub
Example 17: Export data from Excel worksheet (your host application) to an Access
Database Table.
Refer Images 17a, 17b & 17c as mentioned in the code.
Image 17a
Image 17b
Image 17c
Sub AccessDAO_ExportFromExcelToAccess_17()
'Using DAO to Export data from Excel worksheet (your host application) to an Access Database Table.
'refer Image 17a to view the existing SalesManager Table in MS Access file "SalesReport.accdb", indexed on
the "EmployeeId" field.
'refer Image 17b for data in Excel worksheet which is exported to Access Database Table.
'refer Image 17c to view the SalesManager Table in Access file "SalesReport.accdb", after data is exported.
'To use DAO in your Excel VBA project, you must add a reference to the DAO Object Library in Excel (your host
application) by clicking Tools-References in VBE.
'--------------
Dim strMyPath As String, strDBName As String, strDB As String
Dim i As Long, n As Long, lLastRow As Long, lFieldCount As Long
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset
'---------------
'your data source with which to establish connection - ENTER the MS Access Database Name:
strDBName = "SalesReport.accdb"
'get path / location of the database, presumed to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
'set the string variable to the Database:
strDB = strMyPath & "\" & strDBName
Dim ws As Worksheet
'set the worksheet:
Set ws = ActiveWorkbook.Sheets("Sheet9")
'--------------
'COPY RECORDS FROM THE EXCEL WORKSHEET:
'Note: Columns and their order should be the same in both Excel worksheet and in Access database table
lFieldCount = recSet.Fields.count
'determine last data row in the worksheet:
lLastRow = ws.Cells(Rows.count, "A").End(xlUp).Row
'start copying from second row of worksheet, first row contains field names:
For i = 2 To lLastRow
recSet.AddNew
For n = 0 To lFieldCount - 1
recSet.Fields(n).Value = ws.Cells(i, n + 1)
Next n
recSet.Update
Next i
'--------------
'close the objects:
recSet.Close
daoDB.Close
End Sub