按下按钮时,我想执行一个使用变量的SQL语句。
例如:
SELECT a, b,
FROM data
WHERE a IS NOT NULL
AND b = '&<Variable>&';
然后,查询结果将被导出到Excel文件的工作表中。
答案 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