简体   繁体   English

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

[英]Choosing a filepath to export .xlsx file VBA

I'm trying to write a bit of code that allows the user to choose the file path of a folder before exporting data in a separate .xlsx file to that folder. 我正在尝试编写一些代码,允许用户在将单独的.xlsx文件中的数据导出到该文件夹​​之前选择文件夹的文件路径。 Its easy enough to look up a folder's path beforehand and hard code it in, but I want this program to allow the user to choose a folder each time. 它很容易预先查找文件夹的路径并对其进行硬编码,但是我希望该程序允许用户每次选择一个文件夹。 As it is, I have this function that utilizes the excel open file dialog box. 实际上,我具有利用excel打开文件对话框的此功能。 From there, I am able to find the folder I need, and just copy the file path from the top bar and hit cancel. 从那里,我可以找到所需的文件夹,只需从顶部栏中复制文件路径,然后单击“取消”即可。 Here's the code: 这是代码:

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

This does the job, but it seems pretty sloppy, since it forces the user to manually copy the file path needed and then cancel the open file dialog box. 这项工作可以完成,但是看起来很草率,因为它迫使用户手动复制所需的文件路径,然后取消打开文件对话框。 Does anyone know a more creative and clean way about this while still keeping the same functionality? 在保持相同功能的同时,有谁知道更新颖,更简洁的方法吗?

Thanks in advance! 提前致谢!

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

Here's the description: 描述如下:

  1. Application.FileDialog(msoFileDialogFolderPicker) - The folder dialog prompts the user to select a directory path. Application.FileDialog(msoFileDialogFolderPicker) -文件夹对话框提示用户选择目录路径。

  2. strPath - Default path which will be passed on to the function. strPath将传递给函数的默认路径。

  3. show - If the user chooses to cancel the dialog, the value '0' will be assigned, otherwise the value '-1' is assigned. show如果用户选择取消对话框,则将分配值'0',否则将分配值'-1'。

  4. GetFolder = sItem - The path of the folder selected/opened is returned by this statement, else Null is returned if Cancel button is clicked. GetFolder = sItem此语句返回选定/打开的文件夹的路径,否则,如果单击“取消”按钮,则返回Null。

Hope this clears the overall logic used. 希望这能清除使用的整体逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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