12

目前我的代码是这样的:

Dim testSQL As String
Dim qd As DAO.QueryDef

testSQL = "SELECT * FROM qryExample WHERE exampleID IN (" & strExampleIDList & ")"
Set qd = db.CreateQueryDef("tmpExport", testSQL)
DoCmd.TransferText acExportDelim, , "tmpExport", "C:\export.csv"
db.QueryDefs.Delete "tmpExport"

如何更改“C:\export.csv”部分,以便用户能够定义文件路径和文件名?

谢谢。

4

2 回答 2

15

假设您希望提示用户输入,然后在 TransferText 调用中使用该输入,请尝试以下操作:

Dim UserInput As String
UserInput  = InputBox("Please enter the file path.", "I WANT A VALUE!") 
DoCmd.TransferText acExportDelim, , "tmpExport", UserInput  

还有其他方法,但这可能是最容易实现的。

祝你好运。

于 2013-02-05T04:28:59.273 回答
8

此示例将允许您使用 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
于 2014-08-27T14:33:06.757 回答