我试图将需要参数的查询中的数据放入带有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
答案 0 :(得分:1)
Office自动化项目中的奇怪行为通常可能是由于未能正确Close
个对象和Quit
应用程序造成的。在这种情况下添加
wbTarget.Close
和
XL.Quit
陈述似乎解决了这个问题。
答案 1 :(得分:1)
我能看到的唯一问题是没有使用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