I'm exporting the contents of a query to an excel file, opening the file and attempting to make some basic modifications to it. Then saving and closing the file.
I'm have INTERMITTENT issues - sometimes the export and modifications works fine without any errors. Sometimes I get runtime error 462. It's a bit hit & miss, but I think the error occurs if I run the code twice during one "session". If I close the form which calls the code and open and try the command button again - it works. If I don't close/open and just run it twice, I get the error.
My code is below.
Furthermore - and this probably qualifies as a seperate problem - the times it does work, an instance of excel.exe is left open in Task Manager. I'm sure the code is correct for killing these off at the end!
Any help?
I'm have INTERMITTENT issues - sometimes the export and modifications works fine without any errors. Sometimes I get runtime error 462. It's a bit hit & miss, but I think the error occurs if I run the code twice during one "session". If I close the form which calls the code and open and try the command button again - it works. If I don't close/open and just run it twice, I get the error.
My code is below.
Furthermore - and this probably qualifies as a seperate problem - the times it does work, an instance of excel.exe is left open in Task Manager. I'm sure the code is correct for killing these off at the end!
Any help?
Code:
Private Sub Command_Daily_Click()
Dim strOutput As String
strOutput = "D:\Documents and Settings\All Users\Desktop\Daily_Stats.xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qry_DailyStatsExport_Crosstab", strOutput, False
Dim objExcel As Excel.Application
Dim xlBook As Workbook
Dim xlSheet As Worksheet
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
objExcel.EnableEvents = False
objExcel.ScreenUpdating = False
Set xlBook = Workbooks.Open(strOutput)
xlBook.Worksheets("qry_DailyStatsExport_Crosstab").Name = "Daily Stats"
Set xlSheet = xlBook.Worksheets("Daily Stats")
xlSheet.Rows("1:1").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
xlBook.Save
objExcel.DisplayAlerts = True
objExcel.EnableEvents = True
objExcel.ScreenUpdating = True
xlBook.Close
Set xlBook = Nothing
objExcel.Application.Quit
Set objExcel = Nothing
MsgBox "Todays report has been saved to your desktop."
End Sub