You are on page 1of 2

Export Multiple Excel Worksheet from one Access Query

Posted by Dorothea in Microsoft Access on 10-Nov-10 01:02 PM

How do I export an access query (qry_Attorney) to multiple excel


workbooks?  I have  query built with the records assigned by attorney, there
can be multiple attorneys and I need to have a separate worksheet named
for the specific attorney.

Ex.
Client   Attorney   Open Date   Close Date
Jones   Willis      08/01/10
Butler  Willis     09/15/2010
Smith    Holmon   
Travis    Cardman    01/01/2010

So there would be 3 separate excel files named:  Willis 111010.xls; Holman


111010.xls and Cardman 111010.xls

My option now is to export the whole file and create a pivot and separate
from there.

Any help would be appreciated.

Thanks

re: Export Multiple Excel Worksheet from one Access Query


Dale Morrell replied to Dorothea on 16-Nov-10 12:54 AM

I can see 3 solutions:

1. Create a parameter query on the Attourney and export multiple times.


2. Do 1. and automate with vba.
3. Get Excel to pull the data by having a spreadsheet for each Attourney that has a query back to the
database.
Reply

re: Export Multiple Excel Worksheet from one Access Query


Dorothea replied to Dale Morrell on 17-Nov-10 10:18 AM

The attorney list could change day by day so it would be impossible to create a parameter query.  I
would like to create something in VBA but do not have enough experience to do so without help
Reply

re: Export Multiple Excel Worksheet from one Access Query


Dale Morrell replied to Dorothea on 17-Nov-10 11:44 PM

This should do what you want

Private Sub ToExcel_Click()


  'declare variables
  Dim Distinct As Recordset
  Dim Atourneys As Recordset
  Dim sSql As String
  Dim xlApp As Excel.Application
  Dim xlWb As Excel.Workbook
  Dim xlWs As Excel.Worksheet
  Dim r As Excel.Range
  Const path As String = "C:\Path to folder to save\"
    
  'get a recordset of distinct Atourney names
  sSql = "SELECT DISTINCT Attourney FROM Atourneys"
  Set Distinct = CurrentDb.OpenRecordset(sSql, dbOpenSnapshot)
    
  'Open Excel and make it visible
  Set xlApp = New Excel.Application
  xlApp.Visible = True
    
  'Step through each Atourney
  While Not Distinct.EOF
    'Get the records associated with this Atourney
    sSql = "SELECT Client, Attourney, [Open Date], [Close Date] FROM
Atourneys WHERE Attourney='" & Distinct(0) & "'"
    Set Atourneys = CurrentDb.OpenRecordset(sSql, dbOpenSnapshot)
    'Create a new workbook
    Set xlWb = xlApp.Workbooks.Add()
    Set xlWs = xlWb.ActiveSheet
    'Get the range to paste into
    Set r = xlWs.Range("A1")
    'Copy to excel
    r.CopyFromRecordset Atourneys
    'Name the worksheet
    xlWs.Name = Distinct(0)
    'Save the workbook
    xlWb.SaveAs path & Distinct(0) & " " & Format(Now(), "MMDDYY")
    'close the workbook
    xlWb.Close False
    'move to the next Atourney
    Distinct.MoveNext
  Wend
  'Quit excel
  xlApp.Quit
End Sub

You might also like