Public Function SendTQ2ExcelSheet(strTQName As String, strTQName2 As String, strSheetName As String, strSheetName2 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
Dim X As Integer ' count loop
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
10 On Error GoTo err_handler
20 If strFilePath <> "" Then
30 strPath = strFilePath
40 End If
50 Set ApXL = CreateObject("Excel.Application")
60 For X = 1 To 2
70 If X = 1 Then
80 strTQName = strTQName
90 strSheetName = strSheetName
100 Else
110 strTQName = strTQName2
120 strSheetName = strSheetName2
130 End If
140 Set rst = CurrentDb.OpenRecordset(strTQName)
150 If strPath <> "" Then
160 Set xlWBk = ApXL.Workbooks.Open(strPath)
170 Else
180 Set xlWBk = ApXL.Workbooks.Add
190 End If
200 ApXL.Visible = True
210 If strSheetName <> "" Then
220 Set xlWSh = xlWBk.Worksheets(strSheetName)
230 Else
240 Set xlWSh = xlWBk.Worksheets(X)
250 End If
260 If strRange <> "" Then
270 xlWSh.Range(strRange).Select
280 Else
290 xlWSh.Range("A1").Select
300 End If
310 If blnIncludeHeaders Then
320 For Each fld In rst.Fields
330 ApXL.ActiveCell = fld.Name
340 ApXL.ActiveCell.Offset(0, 1).Select
350 Next
360 End If
370 rst.MoveFirst
380 If strRange <> "" Then
390 xlWSh.Range(strRange).CopyFromRecordset rst
400 Else
410 xlWSh.Range("A2").CopyFromRecordset rst
420 End If
430 xlWSh.Range("1:1").Select
' This is included to show some of what you can do about formatting. You can comment out or delete
' any of this that you don't want to use in your own export.
440 With ApXL.Selection.Font
450 .Name = "Arial"
460 .Size = 12
470 .Strikethrough = False
480 .Superscript = False
490 .Subscript = False
500 .OutlineFont = False
510 .Shadow = False
520 End With
530 ApXL.Selection.Font.Bold = True
540 With ApXL.Selection
550 .HorizontalAlignment = xlCenter
560 .VerticalAlignment = xlBottom
570 .WrapText = False
580 .Orientation = 0
590 .AddIndent = False
600 .IndentLevel = 0
610 .ShrinkToFit = False
620 .MergeCells = False
630 End With
' selects all of the cells
640 ApXL.ActiveSheet.Cells.Select
' does the "autofit" for all columns
650 ApXL.ActiveSheet.Cells.EntireColumn.AutoFit
' selects the first cell to unselect all cells
660 xlWSh.Range("A1").Select
670 rst.Close
680 Set rst = Nothing
690 Next X
700 Exit Function
err_handler:
710 DoCmd.SetWarnings True
720 MsgBox Err.Description, vbExclamation, Err.Number
730 Exit Function
End Function