选择导出 .xlsx 文件的文件路径 VBA

Choosing a filepath to export .xlsx file VBA

我正在尝试编写一些代码,允许用户在将单独的 .xlsx 文件中的数据导出到该文件夹​​之前选择该文件夹的文件路径。预先查找文件夹的路径并将其硬编码进去很容易,但我希望这个程序允许用户每次都选择一个文件夹。事实上,我有这个利用 excel 打开文件对话框的功能。从那里,我可以找到我需要的文件夹,只需从顶部栏复制文件路径并点击取消。这是代码:

Function GetFileDestination() As String
    Dim DataObj As New MSForms.DataObject

    'This MsgBox just tells the user what to do
    MsgBox "To get the file Destination, the 'Open File' Dialog Box will open. Go to the folder_
    you want to use, click on the bar at the top, and copy the destination. Then hit Cancel",_
    vbOKOnly, "Finding the File Destination"

    Application.Dialogs(xlDialogOpen).Show
    DataObj.GetFromClipboard
    GetFileDestination = DataObj.GetText
End Function

这样就可以了,但看起来很草率,因为它强制用户手动复制所需的文件路径,然后取消打开文件对话框。 有谁知道在保持相同功能的同时更有创意、更简洁的方法吗?

提前致谢!

Function GetFolder(strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
    .Title = "Select a Folder"
    .AllowMultiSelect = False
    .InitialFileName = strPath
    If .Show <> -1 Then GoTo NextCode
    sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function

描述如下:

  1. Application.FileDialog(msoFileDialogFolderPicker) - 文件夹对话框提示用户 select一个目录路径。

  2. strPath - 将传递给函数的默认路径。

  3. show - 如果用户选择取消对话,将分配值'0',否则分配值'-1'。

  4. GetFolder = sItem - 此语句返回文件夹 selected/opened 的路径, else 如果单击 取消 按钮,则返回 Null。

希望这清除了使用的整体逻辑。