In your first post, you didn't include the function name so I guessed at it.
"Sub Button_Click()" would be how you start the export process. If you clicked a button, that is the code that would execute. Change "Button_Click" to your button (?) name.
I moved (or tried to
) the code that opens/closes Excel to the button click procedure.
The process would be:
- Open Excel
- Export all the data
- Close Excel
WARNING!! This is UNTESTED!!!
Code:
Sub Button_Click()
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim strPath As String
' EXCEL file that is to contain the exported data
strPath = "C:.......\file.xlsx"
Set ApXL = CreateObject("Excel.Application")
Set xlWBk = ApXL.Workbooks.Open(strPath)
ApXL.Visible = True
'export data
Call ExportToSpecificSheet("table1", "sheet1")
Call ExportToSpecificSheet("table2", "sheet2")
Call ExportToSpecificSheet("table3", "sheet3")
Call ExportToSpecificSheet("table4", "sheet4")
Call ExportToSpecificSheet("table5", "sheet5")
' now exit excel
xlWBk.Save
xlWBk.Close
End Sub
'I guessed at this line
Function ExportToSpecificSheet(QueryName As String, strSheetName As String)
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Dim rst As DAO.Recordset
Dim fld As DAO.Field
On Error GoTo Err_Handler
Set rst = CurrentDb.OpenRecordset(QueryName)
Set xlWSh = xlWBk.Worksheets(strSheetName)
xlWSh.Activate
xlWSh.Range("A1").Select
' add field (column) names
For Each fld In rst.Fields
ApXL.ActiveCell = fld.Name
ApXL.ActiveCell.Offset(0, 1).Select
Next
rst.MoveFirst
'copy data to Excel
xlWSh.Range("A2").CopyFromRecordset rst
xlWSh.Range("1:1").Select
ApXL.ActiveSheet.Visible = False
rst.Close
Set rst = Nothing
End Function