How to send parameters to microsoft access query so that I can import an access parameter query to excel?

微笑、不失礼 提交于 2019-12-20 04:25:10

问题


I need to import a microsoft access query that has popup input parameters into excel. I tried the code below but it does not work. I receive error 93 that tells me that object or object variable is not set.

I would like to be able to reference two cells in excel that contain the values of the current and previous month and then send these values as inputs to the access query, but for now I entered them in VBA to keep it simple.

Any help would be greatly appreciated!

Thank you!

Sub Acess_Connection()
     Dim dbs As DAO.Database
     Dim rst As DAO.Recordset
     Dim qdf As DAO.QueryDef
     Dim i As Long
     Dim wsh As Worksheet

     Set dbs = DBEngine.OpenDatabase("filepath")                         
     Set qdf = dbs.QueryDefs("parameter_query")

     qdf.Parameters("Date_PreviousMonth") = "31.12.2018"
     qdf.Parameters("Date_CurrentMonth") = "31.01.2019"

     Set rst = qdf.OpenRecordset("parameter_query")          
     Set wsh = Worksheets("Sheet1")

     For i = 0 To rst.Fields.Count - 1   
         wsh.Cells(1, i + 1).Value = rst.Fields(i).Name      
     Next

     wsh.Range("A1").Resize(ColumnSize:=rst.Fields.Count).Font.Bold = True
     wsh.Range("A2").CopyFromRecordset rst

     rst.Close
     Set rst = Nothing
     dbs.Close
     Set dbs = Nothing
 End Sub

回答1:


I tested setting query parameters via VBA with a very simple query and it works with following adjustments.

  1. query object must have PARAMETERS clause and parameters under appropriate field(s)

  2. use # delimiters for date criteria #12/31/2018#

  3. Set rst = qdf line does not use query name as argument, the variable qdf provides the name so correct to Set rst = qdf.OpenRecordset() which will use the default recordset type.

  4. for early binding, select Microsoft Office 14.0 Access Database Engine Object Library in VBA editor, at least for more recent versions of Excel




回答2:


You may have to pass valid date values to the parameters:

qdf.Parameters("Date_PreviousMonth").Value = #12/31/2018#
qdf.Parameters("Date_CurrentMonth").Value = #01/31/2019#



回答3:


Try adding square brackets around your parameters name so:

qdf.Parameters("[" & "Date_PreviousMonth" & "]") = "31.12.2018"


来源:https://stackoverflow.com/questions/55062692/how-to-send-parameters-to-microsoft-access-query-so-that-i-can-import-an-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!