Excel

Query Access database using ADODB and write results to spreadsheet

Ease of Use

Intermediate

Version tested with

2003 

Submitted by:

mdmackillop

Description:

Insert data from Access to specific location in a workbook 

Discussion:

Extract data from a database for processing with Excel utilities; making charts etc. 

Code:

instructions for use

			

Option Explicit Sub Access_Data() 'Requires reference to Microsoft ActiveX Data Objects xx Library Dim Cn As ADODB.Connection, Rs As ADODB.Recordset Dim MyConn, sSQL As String Dim Rw As Long, Col As Long, c As Long Dim MyField, Location As Range 'Set destination Set Location = [B2] 'Set source MyConn = "C:\AAA\db1.mdb" 'Create query sSQL = "SELECT Table1.Data, Table1.Count FROM Table1;" 'Create RecordSet Set Cn = New ADODB.Connection With Cn .Provider = "Microsoft.Jet.OLEDB.4.0" .Open MyConn Set Rs = .Execute(sSQL) End With 'Write RecordSet to results area Rw = Location.Row Col = Location.Column c = Col Do Until Rs.EOF For Each MyField In Rs.Fields Cells(Rw, c) = MyField c = c + 1 Next MyField Rs.MoveNext Rw = Rw + 1 c = Col Loop Set Location = Nothing Set Cn = Nothing End Sub

How to use:

  1. Paste the code into a standards module
  2. Set the Location and Source to suit
  3. Set the sSql variable to the SQL query code. (Code can be copied from the SQL view of a query created in Access.
 

Test the code:

  1. Copy the attachments into C:\AAA
  2. Open the Excel file
  3. Click the command button
  4. Data items are written to cells B2:C5
 

Sample File:

db1.zip 13.65KB 

Approved by mdmackillop


This entry has been viewed 547 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express