访问VBA - 从查询导出到Excel

时间:2016-04-10 19:48:12

标签: excel-vba ms-access access-vba vba excel

我有一个查询,显示来自2个表的连接记录。现在,我想从该查询中选择具有所需ID的某些记录,并将它们导出到Excel。我怎么能这样做?

这不起作用:

Dim SQL As String

SQL = "SELECT * FROM Created_Query" & _
         " WHERE ID=" & Me![Combobox]

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, SQL, FileName, True

我也尝试过这样的DAO.Recordset:

Dim Desired As Recordset
Dim SQL As String
      SQL = "SELECT * FROM Created_Query" & _
         " WHERE ID=" & Me![Combobox]
Set Desired= CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)

以上方法均无效。我哪里错了?

1 个答案:

答案 0 :(得分:0)

Solved,CreateQueryDef就是我所需要的:)

Dim db As DAO.Database
Dim rs As Recordset
Set db = CurrentDb
Dim mySql As String
mySql = "SELECT * FROM Created_Query" & _
         " WHERE ID=" & Me![Combobox]


db.CreateQueryDef "temp", mySql
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "temp", FileName, True
DoCmd.DeleteObject acQuery, "temp"