Function SendToExcel(strTQName As String, strSheetName As String)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to send it to
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim fld As DAO.Field
Dim lngMaxRow As Long
Dim lngMaxCol As Long
Dim lngLastRow As Long
Dim N As String
Dim strPath As String
Dim qdf As DAO.QueryDef
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlUp As Long = -4162
Const xlDown As Long = -4121
On Error GoTo Err_Handler
strPath = "\UNDISCLOSED_SERVER_PATH\4WeeklyMasterTemplate.xls"
Set qdf = CurrentDb.QueryDefs(strTQName)
qdf![Forms!PayrollPeriodExport!txtPerDate] = [Forms]![PayrollPeriodExport]![txtPerDate]
Set rst = qdf.OpenRecordset()
Set ApXL = CreateObject("Excel.Application")
Set xlWBk = ApXL.Workbooks.Open(strPath)
'Moved to end so Excel doesn't open before the report is finished rendering
'ApXL.Visible = True
Set xlWSh = xlWBk.Worksheets(strSheetName)
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
'xlWSh.Range("D8").CopyFromRecordset rst
' selects the first cell to unselect all cells
xlWSh.Range("A1").Select
rst.CLOSE
Set rst = Nothing
'Remove prompt to save file
ApXL.DisplayAlerts = False
xlWBk.SaveAs "C:\Users\NicolR\Desktop\TEST\FourWeeksEnding_" & Format(Now(), "yyyymmdd") & ".xlsx", 51
ApXL.DisplayAlerts = True
'Open after report is completes
ApXL.Visible = True
ApXL.Quit
Exit Function
Err_Handler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
ApXL.Quit
Set ApXL = Nothing
Exit Function
End Function
Set xlWSh = xlWBk.Worksheets(strSheetName)
Yes, it will overwrite, but you are putting the second query data on another sheet, so not problem there.
I don't know why that line gives an error once in a while. I was thinking it was due to the line
Code:Set xlWSh = xlWBk.Worksheets(strSheetName) [/code[ not executing correctly, but then I'd expect that to raise an error. very hard to debug like this. I'd be looking in the Locals window to see what was assigned. I don't believe that A1 select line is necessary anyway as we are saving and closing the fille, so you could try commenting it out for now at least. Uncomment the call of the first query in the button and try both together. Almost there now. :D[/QUOTE] Hmmm - if it overwrites the file, then will I not lose the sheet it has just saved?
FileCopy "C:\Users\Ron\SourceFolder\Test.xlsx", "C:\Users\Ron\DestFolder\Test_" & Format(Now(), "yyyymmdd") & ".xlsx"
I am struggling with our network at the moment, so its a bit slow for me to post, sorry.
So, under the button, do the file copy (filenames I am happy with), and then call the function?
When calling the function, it is now Call SendToExcel("Queryname", "A2")? - A2 being the cell I want it to start pasting the data into
And the rest looks fine
I will get started on it now