Access Experts

Export Multiple Tables And/Or Queries To Excel

COPY THIS CODE INTO A STANDARD (not form or report) MODULE.  NAME THE MODULE SOMETHING OTHER THAN THIS FUNCTION NAME.

Function SendAllToXLFile(ParamArray strQueries() As Variant)
' Sends multiple tables and/or queries to Excel.
' Instructions:
' 1. Copy this procedure to a standard module
' 2. Make sure the module is not named the same as this procedure
' 3. You can call it by using
'    SendAllToXLFile "Order Summary", "Inventory", "Employees"
' (using the Northwind database as an example this would create a spreadsheet with a tab each for the
' Order Summary and Inventory queries and one for the Employees table.
    Dim objXL As Object
    Dim xlWB As Object
    Dim xlWS As Object
    Dim rst As Object
    Dim lngCount As Long


    Set objXL = CreateObject("Excel.Application")
    objXL.Visible = True
    Set xlWB = objXL.Workbooks.Add


    For lngCount = 0 To UBound(strQueries)
        Set rst = CurrentDb.OpenRecordset(strQueries(lngCount))
        Set xlWS = xlWB.Worksheets.Add
        xlWS.Range("A1").CopyFromRecordset rst
        xlWS.Name = Left(strQueries(lngCount), 32)
        rst.Close
    Next

    Set rst = Nothing
    objXL.UserControl = True
    Set objXL = Nothing
End Function