0

我试图将需要参数的查询中的数据放入带有 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
4

2 回答 2

1

Office 自动化项目中的奇怪行为通常是由于未能正确处理Close对象和Quit应用程序造成的。在这种情况下添加

wbTarget.Close 

XL.Quit 

声明似乎已经解决了这个问题。

于 2013-11-10T17:12:57.690 回答
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
于 2013-11-13T00:03:06.030 回答