Home > other >  Excel VBA Use ADO Command Object to Call Stored Query in Access
Excel VBA Use ADO Command Object to Call Stored Query in Access

Time:02-28

I'm trying to call a stored query in my Access database that requires one parameter (criteria). When I try this I get runtime error '3265': "Item cannot be found in the collection corresponding to the requested name or ordinal" when it reaches the line cmd(1)=userName.

enter image description here

The msgbox line above that one shows me that there is a parameter count of 0, but there should be a count of 1.

Function getUserLevelCmd() As String
 Dim conn As ADODB.Connection
 Dim rs As ADODB.Recordset
 Dim cmd As New ADODB.Command

 Set conn = makeConnection()

 cmd.CommandText = "accessLevelByUN"
 cmd.CommandType = adCmdStoredProc

 cmd.ActiveConnection = conn

 cmd.Parameters.Refresh

 MsgBox (cmd.Parameters.Count)

 cmd(1) = userName

 Set rs = cmd.Execute

 rs.Close
 conn.Close
 Set cmd = Nothing
End Function

I double and triple checked all my spellings. I know that the connection to my database is good, because I am able to use it to do other SQL queries. It's just stored queries that have parameters that I'm stuck on. I based my attempt on this tutorial from Microsoft: enter image description here

The SQL-view of the of the query in access: enter image description here

Anyone have any tips?

CodePudding user response:

adCmdStoredProc doesn't seem to be designed for MsAccess queries. Change it to adCmdTable. Also, when setting the parameter values they are indexed from zero.

 Dim conn As ADODB.Connection
 Dim rs As ADODB.Recordset
 Dim cmd As New ADODB.Command

 Set conn = makeConnection()
 cmd.CommandText = "accessLevelByUN"
 cmd.CommandType = adCmdTable

 cmd.ActiveConnection = conn

 cmd.Parameters.Refresh

 MsgBox (cmd.Parameters.Count)

 cmd.Parameters(0) = userName

 Set rs = cmd.Execute
...
  • Related