Public Function aSendTQ2ExcelSheet(strTQName As String, strSheetName As String, Optional strFilePath As String, Optional strRange As String, Optional blnIncludeHeaders As Boolean)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to send it to
' strRange is where you want the data to start.
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim fld As Field
Dim strPath As String
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
On Error GoTo err_handler
If strFilePath <> "" Then
strPath = strFilePath
End If
Set rst = CurrentDb.OpenRecordset(strTQName)
Set ApXL = CreateObject("Excel.Application")
If strPath <> "" Then
Set xlWBk = ApXL.Workbooks.Open(strPath)
Else
Set xlWBk = ApXL.Workbooks.Add
End If
ApXL.Visible = True
If strSheetName <> "" Then
Set xlWSh = xlWBk.Worksheets(strSheetName)
Else
Set xlWSh = xlWBk.Worksheets(1)
End If
' xlWSh.Range(strRange & ":Z65536").Select
' ApXL.Selection.Clear
If strRange <> "" Then
xlWSh.Activate
xlWSh.Range(strRange & ":Z65536").Select
ApXL.Selection.Clear
xlWSh.Range(strRange).Select
Else
xlWSh.Range("A2").Select
End If
If blnIncludeHeaders Then
For Each fld In rst.Fields
ApXL.Activecell = fld.Name
ApXL.Activecell.Offset(0, 1).Select
Next
xlWSh.Range(strRange).Select
ApXL.Activecell.Offset(1, 0).Select
strRange = ApXL.Activecell.Address
End If
rst.MoveFirst
If strRange <> "" Then
xlWSh.Range(strRange).CopyFromRecordset rst
Else
xlWSh.Range("A2").CopyFromRecordset rst
End If
rst.Close
Set rst = Nothing
'save and close Excel File
xlWBk.Save
ApXL.Application.Quit
Set xlWSh = Nothing
Set xlWBk = Nothing
Set ApXL = Nothing
Exit Function
err_handler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.number
Exit Function
End Function