Sie sind auf Seite 1von 5

Add, Edit, Delete and Run Access Queries and Procedures with VBA

Contents
Introduction Introduction Introduction Introduction
Code to Create a Query or Procedure Code to Create a Query or Procedure Code to Create a Query or Procedure Code to Create a Query or Procedure
Code to Modify a Query or Procedure Code to Modify a Query or Procedure Code to Modify a Query or Procedure Code to Modify a Query or Procedure
Code to Delete a Query or Procedure Code to Delete a Query or Procedure Code to Delete a Query or Procedure Code to Delete a Query or Procedure
Code to Run a Query or Procedure Code to Run a Query or Procedure Code to Run a Query or Procedure Code to Run a Query or Procedure
Examples Examples Examples Examples
- Create a select query
- Create an action query
- Create a parameter query
- Modify a query
- Delete a query
- Run an action query
- Run a select query
- Run a parameter query
- Create a stored procedure
Possible Errors Possible Errors Possible Errors Possible Errors
Further Reading Further Reading Further Reading Further Reading
Introduction
The focus of this article is to demonstrate how to use ADO/ADOX to manipulate Access objects. In truth, generally when
dealing with Microsoft Access, DAO (Data Access Objects) would be a better object library than than ADO. ADOX, however, is
extendible to other databases, not just Microsoft Access.
ADOX (Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security ) is an extension to the ADO
objects and programming model. ADOX includes objects for schema creation and modification, as well as security. It exposes
additional objects for creating, modifying, and deleting schema objects, such as tables and procedures.
ADOX capabilities extend far beyond what is described in this article. For more information on ADOX see the links in Further
Reading.
Code to Create a Query or Procedure
Public Enum ViewOrProc
View
Proc
End Enum
Public Sub CreateQuery(ByVal strDBPath As String, _
ByVal strSql As String, ByVal strQueryName As String, _
ByVal vpType As ViewOrProc)
Dim objCat As Object
Dim objCmd As Object
On Error GoTo exit_point
Set objCat = CreateObject(Class:="ADOX.Catalog")
objCat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
Set objCmd = CreateObject(Class:="ADODB.Command")
objCmd.CommandText = strSql
Concatenate a Range
of Values
Extract a number
from a text string with
LOOKUP
Translate Text in
Excel
Excel Dashboards
using PowerPivot,
Pivot Tables and
Charts
Advanced Excel
Management
Accountants and
Finance Managers
Excel VBA Trainer for
Hire
Wotizit?
MrExcel Google
Search Engine
How to deal with
prank calls
Paragliding
Hermanus
accdb access database
activex data objects
ado advanced excel
array formula autofill backup
bloomberg calculated
columns charts class class
module compact access
compact and repair criteria
dashboards data
visualisation excel
excel course
formula
formulas international
securities identification
number isin jro macros
microsoft
excel Microsoft Jet and
Replication Objects ms
access ms excel
Jon von der Heyden
Excel Developer &
Trainer
View Full Profile
@MrExcel @matthews_p
bigpicturereport.files.wordpress.com/2011/10/cartoo
Jon von der
Heyden
@JONvdHeyden
Expand
@MrExcel @matthews_p
Next time we'll ask the pilot
to do some aerobatics to
Jon von der
Heyden
@JONvdHeyden
27 Nov
27 Nov
Tweets
Follow
Tweet to @JONvdHeyden
EXCEL PARAGLIDING ECO RANDOM SHIZ ABOUT
Jon von der Heyden Excel Add, Edit, Delete and Run Access Queries and Procedures with VBA
Sign Up to see what your friends like. Like Like
RECENT POSTS
TAGS
ABOUT
FOLLOW ME ON TWITTER
Add, Edit, Delete and Run Access Queries with VBA http://jonvonderheyden.net/excel/add-edit-delete-and-run-access-queries-...
1 of 5 3/7/2014 8:25 AM
If vpType = View Then
Call objCat.Views.Append(Name:=strQueryName, Command:=objCmd)
ElseIf vpType = Proc Then
Call objCat.Procedures.Append(Name:=strQueryName, Command:=objCmd)
End If
exit_point:
Set objCat = Nothing
If Err.Number Then
Call Err.Raise(Number:=Err.Number, Description:=Err.Description)
End If
End Sub
Code to Modify a Query or Procedure
Public Enum ViewOrProc
View
Proc
End Enum
Public Sub ModifyQuery(ByVal strDBPath As String, _
ByVal strSql As String, ByVal strQueryName As String)
Dim objCat As Object
Dim objCmd As Object
Dim vpType As ViewOrProc
On Error GoTo exit_point
Set objCat = CreateObject(Class:="ADOX.Catalog")
objCat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
On Error Resume Next
Set objCmd = objCat.Views(strQueryName).Command
If Not objCmd Is Nothing Then
vpType = View
Else
Set objCmd = objCat.Procedures(strQueryName).Command
If Not objCmd Is Nothing Then
vpType = Proc
End If
End If
On Error GoTo exit_point
If objCmd Is Nothing Then GoTo exit_point
objCmd.CommandText = strSql
If vpType = View Then
Set objCat.Views(strQueryName).Command = objCmd
ElseIf vpType = Proc Then
Set objCat.Procedures(strQueryName).Command = objCmd
End If
exit_point:
Set objCat = Nothing
If Err.Number Then
Call Err.Raise(Number:=Err.Number, Description:=Err.Description)
End If
End Sub
Code to Delete a Query or Procedure
Public Sub DeleteQuery(ByVal strDBPath As String, ByVal strQueryName As String)
Dim objCat As Object
Dim lngCount As Long
Set objCat = CreateObject(Class:="ADOX.Catalog")
objCat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"

With objCat
lngCount = .Procedures.Count + .Views.Count
On Error Resume Next
Call .Procedures.Delete(strQueryName)
Call .Views.Delete(strQueryName)
On Error GoTo exit_point
If .Procedures.Count + .Views.Count = lngCount Then
Err.Number = 3265
Err.Description = "Item cannot be found in the collection corresponding to the requested name or ordinal."
End If
End With
exit_point:
Set objCat = Nothing

If Err.Number Then
Call Err.Raise(Number:=Err.Number, Description:=Err.Description)
End If
End Sub
Code to Run a Query or Procedure
Public Function RunQuery(ByVal strDBPath As String, ByVal strQueryName As String, ParamArray parArgs() As Variant) As Object
Dim objCmd As Object
Dim objRec As Object
Dim varArgs() As Variant
Set objCmd = CreateObject("ADODB.Command")
If UBound(parArgs) = -1 Then
varArgs = VBA.Array("")
Else
varArgs = parArgs
End If
With objCmd
.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDBPath & ";" & _
"Jet OLEDB:Engine Type=5;" & _
"Persist Security Info=False;"
.CommandText = strQueryName
If UBound(parArgs) = -1 Then
Set objRec = .Execute(Options:=4)
Else
varArgs = parArgs
Set objRec = .Execute(Parameters:=varArgs, Options:=4)
End If
ms query non repeating
random number pivot
tables rand randbetween
random number sedol stock
exchange daily official list
training udf unique
random number user
defined
function vba
visual basics
for
applications
worksheet function
Add, Edit, Delete and Run Access Queries with VBA http://jonvonderheyden.net/excel/add-edit-delete-and-run-access-queries-...
2 of 5 3/7/2014 8:25 AM
End With
Set RunQuery = objRec
Set objRec = Nothing
End Function
Examples
Create a simple query Create a simple query Create a simple query Create a simple query
Simple queries should be added to the Views Catalog collection.
Public Sub CreateSimpleQuery()
Const strDB As String = "C:Demo.accdb"
Const strSql As String = "SELECT * FROM [Personnel] WHERE [Personnel].[Division]='HR';"
Const strQueryName As String = "qrySimple"

Call CreateQuery(strDB, strSql, strQueryName, View)
End Sub

Create an action query Create an action query Create an action query Create an action query
Action queries should be added to the Views Catalog collection.
Public Sub CreateActionQuery()
Const strDB As String = "C:Demo.accdb"
Const strSql As String = "UPDATE [Personnel] " & _
"SET [Personnel].[LAST_NAME] = Replace([LAST_NAME],""-"","" "") " & _
"WHERE ((([Personnel].[LAST_NAME]) Like ""*-*""));"
Const strQueryName As String = "qryAction"

Call CreateQuery(strDB, strSql, strQueryName, View)
End Sub
I purposely chose to illustrate an action query that utilises the Replace function. Certain functions are not available when
executing SQL from ADO. Replace is one of these. The work-around is to create a query rather than executing the SQL directly
with ADO. Then one can use the method illustrated below to run the query, and delete the query if the query wont be needed
again.

Create a parameter query Create a parameter query Create a parameter query Create a parameter query
Parameter queries should be added to the Procedures Catalog collection.
Public Sub CreateParameterQuery()
Const strDB As String = "C:UsersJon von der HeydenDesktopDesktop Filestest.accdb"
Const strSql As String = "PARAMETERS prmDivision LongText; SELECT * FROM [Personnel] " & _
"WHERE [Personnel].[Division] = prmDivision;"
Const strQueryName As String = "qryParams"

Call CreateQuery(strDB, strSql, strQueryName, Proc)
End Sub

Modify a query Modify a query Modify a query Modify a query
Public Sub ModifyAQuery()
Const strDB As String = "C:Demo.accdb"
Const strSql As String = "UPDATE [Personnel] " & _
"SET [Personnel].[LAST_NAME] = Replace([LAST_NAME],""-"","" "") " & _
"WHERE ((([Personnel].[LAST_NAME]) Like ""%-%""));"
Const strQueryName As String = "qryAction"

Call ModifyQuery(strDB, strSql, strQueryName)
End Sub
Ive used this exhibit to demonstrate the importance of the percentage character (%) as a wildcard character. In Access the
original action query qryAction would utilise an asterisk character (*) as a wildcard character. However, in order for the query
to work from RunQuery, a percentage character is required.

Delete a query Delete a query Delete a query Delete a query
Public Sub DeleteAQuery()
Const strDB As String = "C:Demo.accdb"
Const strQueryName As String = "qryOld"

Call DeleteQuery(strDB, strQueryName)
End Sub

Run an action query Run an action query Run an action query Run an action query
Public Sub RunActionQuery()
Const strDB As String = "C:Demo.accdb"
Const strQueryName As String = "qryAction"

Call RunQuery(strDB, strQueryName)
End Sub

Run a select query Run a select query Run a select query Run a select query
Public Sub RunSelectQuery()
Dim objRec As Object
Dim lngField As Long

Const strDB As String = "C:Demo.accdb"
Const strQueryName As String = "qrySimple"

On Error Resume Next
Set objRec = RunQuery(strDB, strQueryName)
On Error GoTo 0

If Not objRec Is Nothing Then
With Sheet1.Range("A1")
For lngField = 1 To objRec.Fields.Count
.Cells(1, lngField).Value = objRec.Fields(lngField - 1).Name
Next lngField
Add, Edit, Delete and Run Access Queries with VBA http://jonvonderheyden.net/excel/add-edit-delete-and-run-access-queries-...
3 of 5 3/7/2014 8:25 AM
Call .Offset(1, 0).CopyFromRecordset(objRec)
End With
End If

Set objRec = Nothing
End Sub
The typical objective when running a select query is to grab data from a database. What is illustrated here is that the
RunQuery function yields a working recordset. In this exhibit the contents of the recordset are unloaded to Sheet1, however
the recordset can be used in whatever manner one chooses. One may load an array with the recordset (using e.g. GetRows),
or one may Filter the recordset. Whatever

Run a parameter query Run a parameter query Run a parameter query Run a parameter query
Public Sub RunParamQuery()
Dim objRec As Object
Dim lngField As Long

Const strDB As String = "C:Demo.accdb"
Const strQueryName As String = "procPersonnelByDivision"

On Error Resume Next
Set objRec = RunQuery(strDB, strQueryName, "HR")
On Error GoTo 0

If Not objRec Is Nothing Then
With Sheet1.Range("A1")
For lngField = 1 To objRec.Fields.Count
.Cells(1, lngField).Value = objRec.Fields(lngField - 1).Name
Next lngField
Call .Offset(1, 0).CopyFromRecordset(objRec)
End With
End If

Set objRec = Nothing
End Sub
The only difference to take note of here is the use of the RunQuery ParamArray argument. The last argument of RunQuery,
parArgs, allows the coder to pass the parameters to the function. Only one parameter is used here however one could pass
more by separating them with a comma.

Create a stored procedure Create a stored procedure Create a stored procedure Create a stored procedure
Stored Procedures should be added to the Procedures Catalog collection.
Public Sub CreateStoredProc()
Const strDB As String = "C:Demo.accdb"
Const strSql As String = "CREATE PROC procPersonnelByDivision(inDivision VARCHAR) " & _
"AS SELECT * FROM [Personnel] WHERE [Personnel].[Division] = inDivision;"

Const strQueryName As String = "Temp"

Call CreateQuery(strDB, strSql, strQueryName, Proc)
Call RunQuery(strDB, strQueryName)
Call DeleteQuery(strDB, strQueryName)
End Sub
Using the procedures exposed to use from the above, stored procedures can be created by executing a piece of SQL. In this
example, a temporary query is used to house the SQL to create a stored procedure. The temporary query is then executed,
which creates the stored procedure. Finally the temporary query is deleted.
Possible Errors
ERROR REMARK
-2147467259
Could not find file strDBPath.
The database directory or filename is not valid, or it
is inaccessible.
-2147217816
Object strQueryName already exists.
The query already exists in either the Views
collection or Procedures collection.
3265
Item cannot be found in the collection corresponding to
the requested name or ordinal.
The query you are trying to modify, delete or run
does not exist.
-2147467259
The changes you requested to the table were not
successful because they would create duplicate values in
the index, primary key, or relationship. Change the data in
the field or fields that contain duplicate data, remove the
index, or redefine the index to permit duplicate entries
and try again.
The UPDATE or INSERT statement cannot be
executed as it will create forbidden duplicates.
-2147217904
Too few parameters. Expected n.
Ensure ALL parameters are passed to the RunQuery
functions parArgs argument.
-2147217900
Invalid SQL statement; expected DELETE, INSERT,
PROCEDURE, SELECT, or UPDATE.
The SQL statement passed via CreateQuery or
ModifyQuery is invalid.
Further Reading Further Reading Further Reading Further Reading
Microsoft ActiveX Data Objects (ADO)
ADOX Fundamentals
Add, Edit, Delete and Run Access Queries with VBA http://jonvonderheyden.net/excel/add-edit-delete-and-run-access-queries-...
4 of 5 3/7/2014 8:25 AM
Share this:
Like this:
Be the first to like this.
TAGGED
A comprehensive guide to Number Formats in Excel Displaying AutoFilter Criteria
ADO or DAO
ADOX Catalog Object
ADOX Examples Allen Browne
access, activex data objects, ado, adox, adox catalog, excel, microsoft excel, ms access, ms excel, query, run query, sql, stored
procedures, vba, visual basics for applications. BOOKMARK THE PERMALINK.

SEARCH
Enter your email address to subscribe to this
blog and receive notifications of new posts by
email.
EmailAddress
Excel Feed (posts only)
Paragliding Feed (posts only)
Eco Feed (posts only)
All Feeds (posts only)
A comprehensive guide to Number Formats in
Excel
Non Repeating Random Numbers in Excel
Add, Edit, Delete and Run Access Queries and
Procedures with VBA
Concatenate a Range of Values
Compact a MS Access Database from Excel
Advanced Excel - Management Accountants and
Finance Managers
Translate Text in Excel
Preserving a Filtered Recordset
Enable Auto-Fill Formulas in a Protected Table
September 2013
August 2013
July 2013
June 2013
July 2012
June 2012
May 2012
March 2012
POWERED BY PAABOLA & WORDPRESS.
LEAVE A REPLY
Sign Up to see what your friends like. Like Like
SEARCH SUBSCRIBE
RSS
TOP POSTS & PAGES ARCHIVES
Add, Edit, Delete and Run Access Queries with VBA http://jonvonderheyden.net/excel/add-edit-delete-and-run-access-queries-...
5 of 5 3/7/2014 8:25 AM