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

时间:2015-01-06 06:19:24

标签: vba excel-vba excel

我尝试编写一些代码,允许用户在将单独的.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

这可以完成这项任务,但它似乎很草率,因为它强制用户手动复制所需的文件路径,然后取消打开的文件对话框。 有没有人知道更有创意和干净的方式,同时仍然保持相同的功能?

提前致谢!

1 个答案:

答案 0 :(得分:2)

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) - 文件夹对话框提示用户 选择目录路径。

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

  3. show - 如果用户选择取消对话框,则值为&#39; 0&#39;将被分配,否则值为&#39; -1&#39;已分配。

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

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

相关问题