简体   繁体   English

访问 vba 导出查询到新的 excel 工作簿

[英]access vba export query to new excel workbook

I'm trying to write contents of the access query to newly opened excel workbook.我正在尝试将访问查询的内容写入新打开的 excel 工作簿。 Here is the code i tried, it is opening the new excel with empty sheets, not writing the query to sheet.这是我试过的代码,它用空工作表打开新的 excel,而不是将查询写入工作表。

Dim myExcel As Excel.Application
Dim myBook As Excel.Workbook
Dim mySheet As Excel.Worksheet

Set myExcel = CreateObject("Excel.Application")   

Set myBook = myExcel.Workbooks.Add(1)
Set mySheet = myBook.Worksheets(1) 

myExcel.Visible = True   

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, qrytbl1, mySheet, True   

Set myBook = Nothing
Set mySheet = Nothing
Set myExcel = Nothing

You can use the export to spreadsheet function, however keep in mind this writes to a new file.您可以使用导出到电子表格功能,但请记住,这会写入一个新文件。 Not sure if this would work with the file already open.不确定这是否适用于已经打开的文件。 Another approach is using the CopyFromRecordset method after creating the recordset.另一种方法是在创建记录集后使用 CopyFromRecordset 方法。

Here is an example.这是一个例子。

Public Sub DisplayRecordset()
    Dim myrs As DAO.Recordset ' Create a recordset to hold the data
    Dim myExcel As New Excel.Application ' Create Excel with Early binding
    Dim mySheet As Excel.Worksheet

    Set mySheet = myExcel.Workbooks.Add(1).Worksheets(1) ' Create Workbook
    Set myrs = CurrentDb.OpenRecordset("select tbl1.name,tbl1.id,tbl1.ecid FROM tbl1;") ' Define recordset

    'Add header names
    For i = 0 To myrs.Fields.Count - 1
        mySheet.Cells(1, i + 1).Value = myrs.Fields(i).Name
    Next

    'Add data to excel and make Excel visible
    mySheet.Range("**A2**").CopyFromRecordset myrs
    myExcel.Visible = True
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM