Running a query in Access from Excel

sspicer

New Member
Joined
Jun 27, 2008
Messages
48
I know there are similar queries to this already in the forum, but I still can't find the answer to my specific query.

I want to be able to use a button in excel to run a query in access. This cannot be done via putting code into excel and running due to the fact that I have to do this several different times.

Does anyone know what VBA would be needed in order to run a query already written in Access?

Many thanks
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
40,386
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
  2. MacOS
This cannot be done via putting code into excel and running due to the fact that I have to do this several different times.
You lost me here. How can you have a button in Excel to do this if you can't put code in Excel?
 
Upvote 0

Richard Schollar

MrExcel MVP
Joined
Apr 19, 2005
Messages
23,707
Hi

The following uses DAO to connect to the Access db. It runs a query with the name qry_FullConsolidated and returns the data to A2 on the Activesheet:

Code:
Sub ExecuteQuery()
Dim rst As DAO.Recordset, db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = OpenDatabase("Y:\Work\Index Data\IndexData.mdb")
Set qdf = db.QueryDefs("qry_FullConsolidated")
Set rst = qdf.OpenRecordset(dbOpenSnapshot)
Range("A1").CopyFromRecordset rst
End Sub

You must set a referemce to the Microsoft DAO Object library in the VBE (via Tools>References) before you can use this.

Amend database name and path and query name to suit.

Native Access functions such as Nz() in your existing query 9or UDFs you have created yourself) will prevent this from working.
 
Upvote 0

Forum statistics

Threads
1,191,285
Messages
5,985,744
Members
439,979
Latest member
alekun86

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top