此示例将允许您使用 filedialog Save-As 对象:
要使用此功能,您必须添加对“Microsoft Office XX.0 对象库”的引用。添加一个新模块并粘贴以下函数:
Public Sub exportQuery(exportSQL As String)
Dim db As DAO.Database, qd As DAO.QueryDef
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
Set db = CurrentDb
'Check to see if querydef exists
For i = 0 To (db.QueryDefs.Count - 1)
If db.QueryDefs(i).Name = "tmpExport" Then
db.QueryDefs.Delete ("tmpExport")
Exit For
End If
Next i
Set qd = db.CreateQueryDef("tmpExport", exportSQL)
'Set intial filename
fd.InitialFileName = "export_" & Format(Date, "mmddyyy") & ".csv"
If fd.show = True Then
If Format(fd.SelectedItems(1)) <> vbNullString Then
DoCmd.TransferText acExportDelim, , "tmpExport", fd.SelectedItems(1), False
End If
End If
'Cleanup
db.QueryDefs.Delete "tmpExport"
db.Close
Set db = Nothing
Set qd = Nothing
Set fd = Nothing
End Sub
现在在您要开始导出的代码中,使用:调用 exportQuery("SELECT * FROM...")
我建议为您的 SQL 查询定义一个字符串变量。
Public Sub someButton_Click()
Dim queryStr as String
'Store Query Here:
queryStr = "SELECT * FROM..."
Call exportQuery(queryStr)
End Sub