【发布时间】:2017-01-25 20:19:08
【问题描述】:
这个问题相当简单,但让我感到困惑,特别是因为这段代码在我制作的不同应用程序中运行良好,所以我怀疑某处有一些隐藏的设置导致了问题。
我需要将 Access 选择查询的结果传输到模板 Excel 工作表的副本中。此模板中还有一些其他工作表,它们引用将接收 Access 查询数据的工作表,然后对其进行一些格式化和计算。我所需要的只是将这个单一查询的结果转移到正确的工作表中,没有任何格式或任何东西。覆盖整个工作表也可以。
我的问题是,它不是复制到工作表“qryLineItemsExportBuffer”,而是创建一个名为“qryLineItemsExportBuffer1”的新工作表并将查询结果放在那里 - 所以工作簿中的所有引用都是在错误的地方寻找。我也不能使用 DoCmd.TransferSpreadsheet [Range] 参数来定义目标工作表,because this does not work when exporting, only while importing.
这是我的代码 - 它 1. 打开模板,2. 使用新名称保存副本,3. 传输查询结果,然后 4. 打开副本并重新计算/重建链接:
Private Sub cmdExportInvoiceRequestForm_Click()
Dim instExcelTemplate As Object
Dim xlsxInvoiceRequestTemplate As Excel.Workbook
Dim xlsxInvoiceRequestNewName As String
Dim xlsxInvoiceRequestCopy As Excel.Workbook
xlsxInvoiceRequestNewName = Application.CurrentProject.Path & "\" & CustomerName & "-InvoiceRequest-" & Format(Date, "dd-mm-yyyy") & ".xlsx" 'create the name for the new invoice report
MsgBox xlsxInvoiceRequestNewName 'user is shown the name and date
MsgBox Application.CurrentProject.Path 'user is shown the destination folder
'start an Excel instance and open the template workbook.
Set instExcelTemplate = CreateObject("Excel.Application")
Set xlsxInvoiceRequestTemplate = instExcelTemplate.Workbooks.Open(Application.CurrentProject.Path & "\Templates\CustomerInvoiceRequestFormTemplate.xlsx") 'open the invoice report template
xlsxInvoiceRequestTemplate.SaveAs FileName:=(xlsxInvoiceRequestNewName) 'save the template as a new file in the correct directory
instExcelTemplate.Workbooks.Close 'close the Excel instance.
'transfer the qryLineItemsExportBuffer results to the newly created workbook.
DoCmd.TransferSpreadsheet acExport, 10, "qryLineItemsExportBuffer", xlsxInvoiceRequestNewName
'start an excel instance and open the new workbook.
Set instExcelCopy = CreateObject("Excel.Application")
Set xlsxInvoiceRequestCopy = instExcelCopy.Workbooks.Open(xlsxInvoiceRequestNewName)
instExcelCopy.CalculateFullRebuild 'recalculate all values and rebuild links in the workbook. This is necessary because it does not do this when opened manually. Can be done in Excel with CTRL+SHIFT+ALT+F9.
xlsxInvoiceRequestCopy.Save 'save the copy
instExcelCopy.Workbooks.Close 'close the Excel instance.
Set xlsxInvoiceRequestCopy = Nothing
Set instExcelCopy = Nothing
xlsxInvoiceRequestNewName = ""
End Sub
我也不能将任何代码放入 Excel 模板本身,所以我不能让它从新工作表中复制数据。
我错过了什么?
【问题讨论】:
-
只是一个想法 - 您的模板是否已经包含一个(可能是隐藏的)名为“qryLineItemsExportBuffer”的工作表?
-
它确实包含一个具有该名称的空白纸,是的。它必须这样做,因为工作簿模板中的其他工作表具有引用工作表的公式,预计在那里输入数据。但是,如果没有这样的工作表,我就无法获得这些参考资料,否则我会得到#REF!错误。
-
哦,是的,我多么愚蠢!在那种情况下,我猜肯定有一些开关可以确定您的代码是尝试将数据添加到现有工作表还是创建新工作表。你说你已经在另一个应用程序中工作了。它是相同版本的 Access/Excel 吗?您可以尝试将非工作系统的元素替换为工作系统的元素,反之亦然,看看问题出在您的 Access 代码还是 Excel 模板上?
-
嗯。所以我已经尝试用命名的工作表制作一个空白模板,并更改名称,但都没有奏效。但是,刚才起作用的是使用其他应用程序中的 Excel 模板!它会正确地覆盖到工作表中,而不是制作新的工作表。因此,我正在查看旧模板,试图找出设置的差异在哪里,但找不到。我会继续寻找。
-
我一直在深入挖掘前一个应用程序的模板工作表——结果发现有一个名为范围的 Excel 与目标工作表和生成查询同名——所以我没有注意到它正在导出到命名范围,而不是工作表名称或查询名称!谢谢你的建议!