Add, Edit, Delete and Run Access Queries With VBA

download Add, Edit, Delete and Run Access Queries With VBA

of 5

Transcript of Add, Edit, Delete and Run Access Queries With VBA

  • 5/24/2018 Add, Edit, Delete and Run Access Queries With VBA

    1/5

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

    ContentsIntroductionIntroductionIntroductionIntroduction

    Code to Create a Query or ProcedureCode to Create a Query or ProcedureCode to Create a Query or ProcedureCode to Create a Query or Procedure

    Code to Modify a Query or ProcedureCode to Modify a Query or ProcedureCode to Modify a Query or ProcedureCode to Modify a Query or ProcedureCode to Delete a Query or ProcedureCode to Delete a Query or ProcedureCode to Delete a Query or ProcedureCode to Delete a Query or Procedure

    Code to Run a Query or ProcedureCode to Run a Query or ProcedureCode to Run a Query or ProcedureCode to Run a Query or Procedure

    ExamplesExamplesExamplesExamples

    - 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 ErrorsPossible ErrorsPossible ErrorsPossible Errors

    Further ReadingFurther ReadingFurther ReadingFurther 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 ob ject 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 Secur ity ) is an extension to the ADO

    objects and programming mo del. 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 a nd procedures.

    ADOX capabilities extend far beyond what is describe d in this article. For more informa tion on ADOX see the links in Further

    Reading.

    Code to Create a Query or ProcedurePublic Enum ViewOrProc View ProcEnd 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

    accdbaccess database

    activex data objects

    adoadvanced excel

    array formulaautofillbackup

    bloombergcalculated

    columnschartsclassclass

    modulecompact access

    compact and repaircriteria

    dashboardsdata

    visualisationexcelexcel course

    formula

    formulasinternational

    securities identification

    numberisinjromacros

    microsoft

    excelMicrosoft Jet andReplication Objectsms

    accessms excel

    Jon von der Heyden

    Excel Developer &

    Trainer

    View Full Profile

    @MrExcel@matthews_

    bigpicturereport.files.wo

    Jon von der

    Heyden

    @JONvdHeyde

    Expand

    @MrExcel@matthews_

    Next time we'll ask the p

    to do some aerobatics t

    Jon von der

    Heyden

    @JONvdHeyde

    Tweets

    Tweet to @JONvdHe

    EXCEL PARAGLIDING ECO RANDOM SHIZ ABOUT

    Jon von der Heyden Excel Add, Edit, Delete and Run Access Queries and Procedures with VBA

    Sign Upto see what your friends like.LikeLikeRECENT POSTS

    TAGS

    ABOUT

    FOLLOW ME ON TWITT

    Add, Edit, Delete and Run Access Queries with VBA http:// jonvonderheyden.net/excel/add-edit-delete-and-run-acce

    1 of 5 3/7/20

  • 5/24/2018 Add, Edit, Delete and Run Access Queries With VBA

    2/5

    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 IfEnd Sub

    Code to Modify a Query or ProcedurePublic Enum ViewOrProc

    View ProcEnd 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 IfEnd Sub

    Code to Delete a Query or ProcedurePublic 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 IfEnd Sub

    Code to Run a Query or ProcedurePublic 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 querynon repeating

    random numberpivot

    tablesrandrandbetween

    random numbersedolstock

    exchange daily official list

    trainingudfunique

    random numberuser

    defined

    functionvbavisual basics

    for

    applicationsworksheet function

    Add, Edit, Delete and Run Access Queries with VBA http:// jonvonderheyden.net/excel/add-edit-delete-and-run-acce

    2 of 5 3/7/20

  • 5/24/2018 Add, Edit, Delete and Run Access Queries With VBA

    3/5

    End With

    Set RunQuery = objRec

    Set objRec = NothingEnd Function

    Examples

    Create a simple queryCreate a simple queryCreate a simple queryCreate a simple query

    Simple queries should be a dded 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 queryCreate an action queryCreate an action queryCreate 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 Replacefunction. Certain functions are not available when

    executing SQL from ADO. Replaceis one of these. The work-a round 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 queryif the query wont be needed

    again.

    Create a parameter queryCreate a parameter queryCreate a parameter queryCreate 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 queryModify a queryModify a queryModify 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 pe rcentage 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 queryDelete a queryDelete a queryDelete 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 queryRun an action queryRun an action queryRun 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 queryRun a select queryRun a select queryRun 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-acce

    3 of 5 3/7/20

  • 5/24/2018 Add, Edit, Delete and Run Access Queries With VBA

    4/5

    Call .Offset(1, 0).CopyFromRecordset(objRec) End With End If

    Set objRec = NothingEnd 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 ar ray with the recordset (using e.g. GetRows),

    or one may Filter the recordset. Whatever

    Run a parameter queryRun a parameter queryRun a parameter queryRun 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 = NothingEnd 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 param eters to the function. Only one parameter is used here however one co uld pass

    more by separating them with a comma.

    Create a stored procedureCreate a stored procedureCreate a stored procedureCreate 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 strQueryNamealready 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 re quested 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 CreateQueryor

    ModifyQueryis invalid.

    Further ReadingFurther ReadingFurther ReadingFurther 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-acce

    4 of 5 3/7/20

  • 5/24/2018 Add, Edit, Delete and Run Access Queries With VBA

    5/5

    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.

    SEARCHEnter 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 Upto see what your friends like.LikeLike

    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-acce

    5 of 5 3/7/20