Public Sub TransferMultipleSpreadsheet(TableName As String, FileName As String, Optional HasFieldNames As Boolean = False)
Const strcDataSheetPrefix As String = "Data"
Dim objExcel As Object
Dim objWorkbook As Object
Dim objWorksheet As Object
Dim objRange As Object
Dim rstData As DAO.Recordset
Dim lngRows As Long, lngSheets As Long
Dim lngCounter As Long
'Open the source recordset and check for records
Set rstData = CurrentDb.OpenRecordset(TableName, dbOpenForwardOnly)
If rstData.BOF Then
MsgBox "There are no records to export", vbCritical, "TransferMultipleSpreadsheet"
GoTo TransferMultipleSpreadsheet_Exit
End If
'END Open the source recordset
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add
'Delete the default worksheets leaving only one, which we grab
On Error Resume Next
objExcel.DisplayAlerts = False
For Each objWorksheet In objWorkbook.worksheets
objWorksheet.Delete
Next objWorksheet
objExcel.DisplayAlerts = False
On Error GoTo 0
Set objWorksheet = objWorkbook.worksheets(1)
'END Delete the default worksheets leaving only one, which we grab
Do
'Check if a new worksheet needs to be added and rename
If objWorksheet Is Nothing Then
Set objWorksheet = objWorkbook.worksheets.Add
End If
lngSheets = lngSheets + 1
objWorksheet.Name = strcDataSheetPrefix & Format$(lngSheets, "00")
'END Check if a new worksheet needs to be added and rename
'Write the field names and determine where to output data & _
and how many rows.
If HasFieldNames Then
For lngCounter = 0 To rstData.Fields.Count - 1
objWorksheet.Cells(1, lngCounter + 1) = rstData.Fields(lngCounter).Name
Next lngCounter
Set objRange = objWorksheet.Range("A2")
lngRows = 65535
Else
objRange = objWorksheet.Range("A1")
lngRows = 65536
End If
'END Write the field names ...
'Output the data, CopyFromRecordset moves the cursor in rstData after copy
objRange.CopyFromRecordset rstData, lngRows
DoEvents
'END Output the data...
'This will tell the loop to create a new worksheet
Set objWorksheet = Nothing
Loop Until rstData.EOF
TransferMultipleSpreadsheet_Exit:
On Error Resume Next
rstData.Close
Set rstData = Nothing
Set objRange = Nothing
objWorkbook.SaveAs FileName
objWorkbook.Close
Set objWorkbook = Nothing
objExcel.Quit
Set objExcel = Nothing
End Sub