简体   繁体   中英

vba - export Access table to file named by user

I'm currently exporting a table in Access 2013 to an Excel file using TransferSpreadsheet. I set the default filename and location. It's working fine, except that when the user changes the name they want to save the file as in the Save As dialog, the is not saved with that name. Is there a way I can get the file name the user entered in the Save As dialog and save the file with that name in the location they select?

Here's what I'm doing now:

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

Thanks in advance.

The SelectedItems() collection contains the list of filenames entered/selected. Since you're using the msoFileDialogSaveAs option, the FileDialog will permit only one selected item. So when .Show is True, just assign .SelectedItems(1) to your strFullPath variable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM