Option Compare Database
Option Explicit
Sub ExportAndPrintFromAccess()
' Temp workbook's name
Const szTempbook As String = "\Temp.xls"
' Access query where the info comes from
Const szQueryName As String = "qryInfo"
' Temp book is created in the same location as this db
' so we build a valid path for it
Dim szFullTempPath As String
szFullTempPath = CurrentProject.Path & szTempbook
On Error Goto ErrHandle
With Application
.Echo False
' Output the query to our Excel book
DoCmd.OutputTo acOutputQuery, szQueryName, acFormatXLS, szFullTempPath, False
' Late binding to avoid reference:
Dim xlApp As Object 'Excel.Application
Dim xlWB As Object 'Workbook
Dim xlWS As Object 'Worksheet
' Create the instance of Excel that we will use to open the temp book
Set xlApp = CreateObject("Excel.Application")
Set xlWB = xlApp.Workbooks.Open(szFullTempPath)
Set xlWS = xlWB.Worksheets(szQueryName)
' Format our temp sheet
' ***************************************************************************
xlApp.Range("A1").Select
Const xlLandscape As Long = 2
Const xlCenter As Long = -4108
With xlWS.PageSetup
.CenterHeader = "&""Arial,Bold""&14PRINTED TEMP REPORT "
.RightFooter = "&D"
.PrintHeadings = False
.PrintGridlines = False
.CenterHorizontally = True
.Orientation = xlLandscape
.Draft = False
End With
With xlWS
.UsedRange.HorizontalAlignment = xlCenter
.UsedRange.Rows.RowHeight = 15.25
End With
' ***************************************************************************
' Select to make sure the sheet has focus
xlWS.Range("A1").Select
' ###########################################################################
' REMOVE THE NEXT 2 LINES (ONLY USED FOR EXAMPLE)
xlApp.Visible = True
xlWS.PrintPreview
' ###########################################################################
' ***************************************************************************
' Uncomment the next line to print the formatted data
' The above section should be removed!
'xlWS.PrintOut
' ***************************************************************************
' Close the file we created
xlWB.Close False
' Since it's a temp, destroy it
Kill szFullTempPath
ErrorExit:
' Explicitly Clear Memory
Set xlWS = Nothing
Set xlWB = Nothing
Set xlApp = Nothing
.Echo True
End With
Exit Sub
ErrHandle:
MsgBox Err.Description
Goto ErrorExit
End Sub
|