The following opens a blank Excel file (or a template, if you want to create one) and populates it with the data from a query.
I tried using code to open a new Excel process each time, but I kept getting 'rogue' processes left over after everything had finished. Unfortunately, noone on the forum was able to tell me how to get rid of them, but this method works fine.
If you do a bit of reading around formatting the spreadsheet, once opened, via VBA, you can just reuse the same blank sheet and there is no need to create any templates.
Hope it makes sense.
Dim myrecs as Recordset
Dim strSQL as string
Dim strTitle as String
Dim str_New_File as string
Dim CellRef as Integer
Dim str_Location as string
strSQL = whatever the query is
strLocation = filepath to blank Excel file or template
strTitle = name of Excel file
Set myrecs = CurrentDb.OpenRecordset(strSQL)
If myrecs.EOF Then
MsgBox "No records found matching the specified criteria"
GoTo End_Function
End If
'Open the relevant Excel template
'--------------------------------
Set ExcelBook = Workbooks.Open(str_Location & str_Title)
Set ExcelSheet = ExcelBook.Worksheets(1)
CellRef = 7
If li_Type = 1 Then
With myrecs
.MoveFirst
ExcelSheet.Range("A3") = Date
Do While Not .EOF
With ExcelSheet
.Range("A" & CellRef & "").Value = myrecs![something]
.Range("B" & CellRef & "").Value = myrecs![something 2]
etc.
End With
CellRef = CellRef + 1
.MoveNext
Loop
End With
str_New_File = new file name & ".xls"
ExcelBook.Application.DisplayAlerts = False
ExcelBook.SaveAs str_New_File
ExcelBook.Application.Quit