Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Query from Access via Excel Query in VBA

Access has saved a query that was designed with the query builder called 'myQuery'. The database is connected to the system via ODBC connection. Macros are all enabled.

Excel Has makes a ADODB connection to connect to the database via

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
 .Provider = "Microsoft.ACE.OLEDB.12.0"
 .Open "MyDatabase.accdb"
End With

Usually you would go ahead and just write your SQL, which is perfectly fine and then just do something like

Dim sqlQuery As String
sqlQuery = "SELECT * FROM myTable"
Set rs = New ADODB.Recordset
rs.Open sqlQuery, con, ...

But I want to access the query that I saved in the access database. So how do I call the saved query in the database that I just connected.

Tried already

  1. con.Execute("EXEC myQuery") but that one told me it could not be find myQuery.
  2. rs.Open "myQuery", con but that one is invalid and wants SELECT/etc statements from it
like image 935
toxicate20 Avatar asked Nov 19 '25 01:11

toxicate20


1 Answers

I think you can treat it like a stored procedure.

If we start right before Dim sqlQuery As String

 Dim cmd as new ADODB.Command
 cmd.CommandType = adCmdStoredProc
 cmd.CommandText = "myQuery"
 cmd.ActiveConnection = con

 Set rs = cmd.Execute()

Then pickup your recordset work after this.

like image 113
Bmo Avatar answered Nov 21 '25 13:11

Bmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!