Option Compare Database
Option Explicit
Public Function fCreate_Excel()
'Creates an Excel file and populates it with query data.
'Uses Late-Binding as there is no way to know ahead of time which version of Excel
'the user will have and which Excel Object Library they will require.
On Error GoTo errCreate_XL
Dim xlApp As Object
Dim xlWB As Object
Dim xlWS As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.UserControl = False
xlApp.SheetsInNewWorkbook = 1 'Only one Worksheet. Why does XL default to 3? What a 'hassle!
xlApp.Workbooks.Add
Set xlWS = xlApp.Worksheets(1)
Call fXL_Export_Recs(xlApp, xlWS) 'Populate Worsheet with data
xlApp.UserControl = True
Set xlWS = Nothing 'Release all objects
Set xlWB = Nothing
Set xlApp = Nothing
Exit Function
errCreate_XL:
xlApp.WindowState = -4140 'Minimize Excel
Set xlWS = Nothing 'Release all objects
Set xlWB = Nothing
Set xlApp = Nothing
MsgBox "An Error Occurred While Attempting To Create Your Excel File."
End Function
Public Function fXL_Export_Recs(xlExport_App As Object, xlExport_WS As Object)
'Routine to grab data and place it in Excel
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim fldcount, iCol As Long
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM qryNDRS_Results")
fldcount = rs.Fields.Count 'Populate XL with column Headings
For iCol = 1 To fldcount
xlExport_WS.cells(1, iCol).Value = rs.Fields(iCol - 1).Name
Next
xlExport_WS.cells(2, 1).copyfromrecordset rs 'Copy recordset to XL
Set rs = Nothing
Set db = Nothing
End Function