使用 Access VBA 将查询导出到新的 Excel 工作簿

Export query to new Excel workbook using Access VBA

我正在尝试将 Access 查询的内容写入新打开的 Excel 工作簿。

代码正在打开 sheet 为空的新 Excel 工作簿,而不是将查询写入 sheet。

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

您可以使用导出到电子表格功能,但请记住,这会写入一个新文件。不确定这是否适用于已打开的文件。另一种方法是在创建记录集后使用 CopyFromRecordset 方法。

这是一个例子。

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