我试图将需要参数的查询中的数据放入带有 marcos 的 excel 模板中,但是我不断收到错误。我从表单中获取参数。这是我的代码:
Private Sub exportButton_Click()
Dim XL As Excel.Application
Dim wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
'Set up refernce to the query to export
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
'Execute Query
Set rsResults = qdfResults.OpenRecordset()
'reference excel
Set XL = CreateObject("Excel.Application")
'refernce workbook
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documen…\folder\resultTemplate.xltm")
'clear excel sheet
wbTarget.Worksheets("marktable").Cells.ClearContents
'paste data from query to worksheet
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
'save workbook
** 1) 'wbTarget.SaveAs ("C:\Users\user\Documents
\folder\resultTemplate1.xlsm")
** 2) wbTarget.SaveAs FileName:="C:\Users\user\Documents\folder\resultTemplate1.xlsm",
FileFormat:=xlOpenXMLWorkbookMacroEnabled
'clear variables
Set wbTarget = Nothing
Set XL = Nothing
Set qdfResults = Nothing
End Sub
1)我可以将数据放入工作簿,但没有宏 2)我可以将数据放入宏,但无法正确保存
有什么建议么?
编辑**不会正确保存我的意思是它正在创建一个我无法保存的临时文件,现在它甚至不会创建它,现在它创建一个 0 字节且没有类型的文件
还不能回答自己的问题,但直到我能继承我的工作代码:
我能看到的唯一问题是 wbTarget.Close 和 XL.Quit 没有使用,这导致模块仍然运行,因此文件没有完全保存,而是临时的。感谢@Gord Thompson
Private Sub exportButton_Click()
Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
Set XL = New Excel.Application
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit
End Sub