To explain. I'm trying to open an Excel workbook, update its data from the database, save it to a folder and with a filename chosen by the user. All good so far. Code runs fine on first iteration but then fails with runtime error 91 on second iteration (and presumably the following ones). Testing shows that, on the second iteration, while the workbook opens and is visible, the is no active workbook (?) thus causing the error. The fail happens at "activeworkbook.refreshall". Any help much appreciated, (oh, I have tried commenting out the set XlApp=nothing line),code below:
Code:
Private Sub update_all_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim prm As DAO.Parameter
Dim lngRowsAffected As Long
Dim lngRowsDeleted As Long
Dim fileName As Variant
Set db = CurrentDb
fileName = Dir("\\Svrfiles\access databases\Portfolio Test\")
While fileName <> ""
DoCmd.OpenQuery "QryDeleteCash", acViewNormal
On Error GoTo 0
DoCmd.TransferSpreadsheet acLink, , "TblInputSht", "\\Svrfiles\access databases\Portfolio Test\" & fileName, False, "Input Sheet!D6:E32"
DoCmd.TransferSpreadsheet acLink, , "TblInputShtName", "\\Svrfiles\access databases\Portfolio Test\" & fileName, False, "Input Sheet!E3:E3"
Set qdf = db.QueryDefs("QryImport2")
db.Execute "QryImport2", dbFailOnError
For Each prm In qdf.Parameters
prm = Eval(prm.Name)
Next prm
qdf.Execute
lngRowsAffected = db.RecordsAffected
DoCmd.DeleteObject acTable, "TblInputShtName"
DoCmd.DeleteObject acTable, "TblInputSht"
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
Set wbOutput = xlApp.Workbooks
xlApp.Visible = True
xlApp.Workbooks.Open "\\Svrfiles\ACCESS DATABASES\cashrptgraph.xlsm", True, False
ActiveWorkbook.RefreshAll
TWait = Time
TWait = DateAdd("s", 10, TWait)
Do Until TNow >= TWait
TNow = Time
Loop
fsName = Excel.Application.GetSaveAsFilename
ActiveWorkbook.SaveAs fileName:=fsName
ActiveWorkbook.Close
xlApp.Quit
Set xlApp = Nothing
fileName = Dir
If fileName <> "" Then
DoCmd.OpenQuery "QryDeleteCash", acViewNormal
End If
Wend
End Sub