vba - export访问用户指定的文件到表

时间:2015-08-11 15:58:20

标签: vba access-vba

我目前正在使用TransferSpreadsheet将Access 2013中的表导出到Excel文件。我设置了默认的文件名和位置。它工作正常,只是当用户更改要保存文件的名称时,如同“另存为”对话框一样,不会使用该名称保存。有没有办法可以获取用户在“另存为”对话框中输入的文件名,并将该文件名保存在他们选择的位置?

这就是我现在正在做的事情:

Dim strTableName As String
Dim strBasePath As String
Dim strFullPath As String
Dim strFileName As String
Dim dlgSaveAs As Object
Const msoFileDialogSaveAs = 2

With CodeContextObject
    strTableName = "New_Rules"
    strBasePath = "C:\Users\" & Environ("USERNAME") & "\Documents\"
    strFileName = "New_Account_Rules_" & Format(Date, "yyyy-mm-dd")
    strFullPath = strBasePath & strFileName & ".xls"
    ' Display the Save As dialog with a default name and path
    Set dlgSaveAs = Application.FileDialog(msoFileDialogSaveAs)
    With dlgSaveAs
        .InitialFileName = strFullPath
        If dlgSaveAs.Show Then
            ' Do the export
            DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "New_Rules", strFullPath, True
        End If
    End With

提前致谢。

1 个答案:

答案 0 :(得分:1)

SelectedItems()集合包含输入/选择的文件名列表。由于您使用 msoFileDialogSaveAs 选项,FileDialog将只允许一个选定项目。因此,当.Show为True时,只需将.SelectedItems(1)分配给strFullPath变量:

With dlgSaveAs

    ' Set the initial/default filename...
    .InitialFileName = strFullPath

    If .Show Then

        ' Get the selected/entered filename...
        strFullPath = .SelectedItems(1)

        ' Do the export...
        DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "New_Rules", strFullPath, True

    End If
End With