Excel VBA Code to get data from MS Access

atuljadhavnetafim

Active Member
Joined
Apr 7, 2012
Messages
341
Office Version
  1. 365
Platform
  1. Windows
Hi Expert

I am using below VBA code to get data from the Access database query with parameter [chooseregion]
this code working fine but when I change the region which has less data it is not clear for previous region data.
For e.g. Region1 has 1000 line items but when I change region to Region2 which has 500 line items in the database, the result shows the first 500 data correct but the next 500 data show from Region1

is there a way so that when I change the region, macro first clears all the existing line items and then shows data for the new region?
also need help, when I change the region I need to run the macro manually, is there any way so whenever cell F6 value changes the macro run automatically.


Sub AccParam() 'Excel VBA to import a parameter query from Access into Excel
Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset

Set MyDatabase = DBEngine.OpenDatabase("D:\Database1.accdb") 'DB Name
Set MyQueryDef = MyDatabase.QueryDefs("Query1") 'Query Name

Sheet1.[A1].CurrentRegion.ClearContents 'Range to Clear
MyQueryDef.Parameters("[ChooseRegion]") = Sheet1.[f6].Value
Set MyRecordset = MyQueryDef.OpenRecordset 'Open the query
Sheet1.Range("A11").CopyFromRecordset MyRecordset

End Sub
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.

Forum statistics

Threads
1,214,419
Messages
6,119,389
Members
448,891
Latest member
tpierce

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
Back
Top