Summary
GetFilePath () returns a full path to a file. If we want a path to a folder instead, we can always use the GetFilePath() command, have the user pick any file in the target folder, and then manipulate the file path to get the parent folder. The following code returns the folder path directly and provides a cleaner interface to the user:
Code Snippets
Option Explicit Sub Main Debug.Clear Dim FO, currFolder As Object Set FO = CreateObject( "Scripting.FileSystemObject") Set currFolder = BrowseForFolder(FO) If currFolder Is Nothing Then MsgBox( "BrowseForFolder failed to get a folder",vbOkOnly, "Error Window") Else Debug. Print "Selected Folder = " & currFolder.Name End If End Sub 'BrowseForFolder returns a FileSystemObject folder Public Function BrowseForFolder(FO As Object) As Object Dim selectedFolder As Object 'Need to add reference: Microsoft Shell Controls And Automation Dim shlShell As Shell32.Shell Dim shlFolder As Shell32.Folder Const BIF_RETURNONLYFSDIRS = &H1 If shlShell Is Nothing Then Set shlShell = New Shell32.Shell End If Set shlFolder = shlShell.BrowseForFolder(Me.hWnd, "Select a Directory", BIF_RETURNONLYFSDIRS) If shlFolder Is Nothing Then MsgBox( "Error getting folder",vbOkOnly, "Error") Set BrowseForFolder = Nothing Else Set selectedFolder = FO.GetFolder(shlFolder.Items.Item.Path) Set BrowseForFolder = selectedFolder End If End Function
Strictly for example purposes, this code simply prints the target folder information to the "Immediate" window (using Debug.Print). In a real application, you would change this to use the folder path as needed in your program.
The comment near the top of the BrowseForFolder() function is critical. To use the file systems objects, you must add a reference for the "Microsoft Shell Controls and Automation" library. To get this dialog, go to EDIT→REFERENCES on the scripting editor menu and check the box for the indicated library.