[英]How do I export 2 queries to a single worksheet in excel from access
I'm using TransferSpreadsheet to export a query from access to excel and it works fine. 我正在使用TransferSpreadsheet从对excel的访问权限中导出查询,并且工作正常。
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qryName", "test1.xls", True
Now I've got another query and I want to add the data from this query to the same worksheet. 现在,我有另一个查询,我想将此查询中的数据添加到同一工作表中。 How can I do this?
我怎样才能做到这一点?
For my first query I use 对于我的第一个查询,我使用
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qryNameFirst", "test1.xlsx", True, "MyWorksheetName"
For the second query I put it in a recordset 对于第二个查询,我将其放在记录集中
Dim rstName As Recordset
Set rstName = CurrentDb.OpenRecordset("qryNameSecond")
Then I just copy this recordset to the worksheet with CopyFromRecordset. 然后,我仅使用CopyFromRecordset将记录集复制到工作表中。
Dim objApp As Object, objMyWorkbook As Object, objMySheet As Object, objMyRange As Object
Set objApp = CreateObject("Excel.Application")
Set objMyWorkbook = objApp.Workbooks.Open("test1.xlsx")
Set objMySheet = objMyWorkbook.Worksheets("MyWorksheetName")
Set objMyRange = objMySheet.Cells(objApp.ActiveSheet.UsedRange.Rows.Count + 2, 1)
With objMyRange
rstName.MoveFirst 'Rewind to the first record
.Clear
.CopyFromRecordset rstName
End With
objApp.ActiveSheet.UsedRange.Rows.Count will return the last used row number. objApp.ActiveSheet.UsedRange.Rows.Count将返回最后使用的行号。 I added + 2 because I want an empty row in between the two queries.
我添加了+ 2,因为我希望两个查询之间有一个空行。
To add I did a performancetest. 另外,我进行了性能测试。 I tested this method with 500.000 records.
我用500.000条记录测试了此方法。 The table containing 500k rows, the first query containing 250k rows, the second query (with the OpenRecordSet) containing 250k rows.
该表包含500k行,第一个查询包含250k行,第二个查询(带有OpenRecordSet)包含250k行。 It took about 10 seconds to generate the excel file sheet and display the data on a E6600 (2,40 Ghz), 4GB ram machine with access/excel 2010.
生成excel文件表并在具有access / excel 2010的E6600(2,40 Ghz),4GB内存计算机上显示数据需要大约10秒钟。
EDIT: 编辑:
Another way to accomplish the same would be with using TransferSpreadsheet 2 times. 实现此目的的另一种方法是使用TransferSpreadsheet 2次。
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qryNameFirst", "test1.xlsx", True, "MyWorksheetName"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qryNameSecond", "test1.xlsx", True, "MyWorksheetName2"
This will create 2 Sheets in the workbook, then just copy the data of one worksheet to the other. 这将在工作簿中创建2个工作表,然后将一个工作表的数据复制到另一个工作表。 I think the performance will be the same but not sure, I will stick with the OpenRecordSet.
我认为性能会相同,但不确定,我会坚持使用OpenRecordSet。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.