使用变量访问查询并导出到Excel

时间:2015-04-23 09:20:02

标签: vba

按下按钮时,我想执行一个使用变量的SQL语句。

例如:

SELECT a, b, 
FROM data 
WHERE a IS NOT NULL 
  AND b = '&<Variable>&';

然后,查询结果将被导出到Excel文件的工作表中。

1 个答案:

答案 0 :(得分:1)

您可能必须动态创建SQL并将其保存为DoCmd.OutputTo方法以便为您执行导出。像。的东西。

Option Compare Database
Option Explicit

Sub ExportQueryToExcel()
    Dim dbObj As DAO.Database, qdObj As DAO.QueryDef
    Dim filePath As String, sqlText As String, yourVariable As String
    Set dbObj = CurrentDb

    yourVariable = "Apple"

    sqlText = "SELECT a, b, c WHERE a Is Not Null And b = '" & yourVariable & "'"
    filePath = "C:\Users\P\Desktop\fileName.xlsx"

    On Error Resume Next
    With dbObj      
        .QueryDefs.Delete "tmpDataQry"
        Set qdfNew = .CreateQueryDef("tmpDataQry", sqlText)
        .Close
    End With
    On Error GoTo 0

    DoCmd.OutputTo acOutputQuery, "tmpDataQry", acFormatXLSX, filePath

    Set qdObj = Nothing
    Set dbObj = Nothing
End Sub