Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the initial path of msoFileDialogFolderPicker

Tags:

excel

vba

The application I am working on requires the users to select a folder using msoFileDialogFolderPicker, and it rather usefully opens the folder picker in the last location. However, our users occasionally change a folder name in the path. This causes a windows 'location unavailable' dialog box. This scares our users as they don't know what's happening.

My question is, how do I find out what the initial folder location is going to be? I can then trap for it just set it to a default location instead.

My code very simply is

GetFolder As String
Set folder = Application.FileDialog(msoFileDialogFolderPicker)

With folder
    .Title = "Please Select a Folder"
    .InitialFileName = "C:\"
    .AllowMultiSelect = False

    If .Show <> -1  Then Goto EndSub
    GetFolder = .SelectedItems(1)
End With

Thanks

like image 260
Smittey Avatar asked Oct 30 '25 09:10

Smittey


1 Answers

Would rather comment to respond to a comment in the previous answer, but I don't have the "reputation" to do that, so forgive me for using one answer to respond to another.

I discovered a subtlety in .InitialFileName. When I use this snippet,

With Application.FileDialog(msoFileDialogFolderPicker)
    .InitialFileName = "C:\Users\" & Environ$("Username") & "\Desktop"
    If .Show = -1 Then
        Get_Folder = .SelectedItems(1)
    Else
        Get_Folder = ""
    End If
End With

VBA puts "Desktop" in the "Folder name:" box at the bottom of the dialog window, and simply defaults to the previous folder used in Windows. But when I put a backslash at the end of the path, as I do here,

With Application.FileDialog(msoFileDialogFolderPicker)
    .InitialFileName = "C:\Users\" & Environ$("Username") & "\Desktop\"
    If .Show = -1 Then
        Get_Folder = .SelectedItems(1)
    Else
        Get_Folder = ""
    End If
End With

the Folder Dialog does not use the last used folder, it actually selects the folder "C:\Users<Username>\Desktop". Having so much depend on a simple backslash is not the best design, but I doubt Microsoft will change that.

like image 105
David Lambert Avatar answered Nov 02 '25 19:11

David Lambert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!