Sub ExportTableToExcel(ByVal TableName As String, ByVal ExcelFile As String, Optional ByVal SheetName As String = "")
' Note:
' ExcelFile should contain the full path and excel workbookname.xlsx
'
Dim appExcel As Object
Dim wb As Object
Dim ws As Object
Dim rs As Recordset
Dim strSQL As String
Dim i As Integer
Dim j As Integer
' Create instance of Excel application
Set appExcel = CreateObject("Excel.Application")
'appExcel.Visible = True ' You can set this to False if you don't want Excel to be visible
' Create a new workbook
Set wb = appExcel.Workbooks.Add
' Define your table query
strSQL = "SELECT * FROM [" & TableName & "];"
' Open recordset
Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot, dbReadOnly)
' Add a new worksheet
Set ws = wb.Worksheets.Add
If Len(SheetName) <> 0 Then
ws.Name = SheetName
Else
ws.Name = TableName
End If
If Not (rs.BOF And rs.EOF) Then
rs.MoveFirst
End If
' Write field names to Excel
For i = 0 To rs.Fields.Count - 1
ws.Cells(1, i + 1).Value = rs.Fields(i).Name
Next i
' Write recordset data to Excel
i = 1
Do While Not rs.EOF
i = i + 1
For j = 0 To rs.Fields.Count - 1
ws.Cells(i, j + 1) = rs.Fields(j)
Next j
rs.MoveNext
Loop
' Save the workbook as xlsx file
wb.SaveAs ExcelFile ' Change the path as needed
' Clean up
wb.Close
appExcel.Quit
Set rs = Nothing
Set ws = Nothing
Set wb = Nothing
Set appExcel = Nothing
MsgBox "Export Complete"
End Sub