Skip to main content

Get a folder

This function will open a dialog that will display the folders on your computer which you can then choose one from.  The second form only opens at the working directory level.

Snippet

Function getFolder()
    Dim BrowseFolder As String
    Dim oFolder, oFolderItem
    Dim oPath, oShell, strPath
    
    Set oShell = CreateObject( "Shell.Application" )
    Set oFolder = oShell.Namespace(17) 'the 17 indicates that we are looking at the virtual folder that contains everything on the local computer
    Set oFolderItem = oFolder.Self
    Set strPath = oFolderItem.Path
    Set oFolder = oShell.BrowseForFolder(0, "Please select the folder where the files are located:", 1, strPath)
    If (Not oFolder is Nothing) Then
        Set oFolderItem = oFolder.Self
        oPath = oFolderItem.Path
        
        If Right(oPath, 1) <> "\" Then
            oPath = oPath & "\"
        End If
    
    End If
    
    getFolder = oPath
   
End Function

Function getFolder() 'this one uses the working directory as the highest level directory
    Dim BrowseFolder As String
    Dim oFolder, oFolderItem
    Dim oPath, oShell, strPath
    Dim Current As Variant 'per Windows documentation this is defined as a variant and not a string
    
    
    Set oShell = CreateObject( "Shell.Application" )
    Set oFolder = oShell.Namespace(17) 'the 17 indicates that we are looking at the virtual folder that contains everything on the local computer
    Current = Client.WorkingDirectory()
    Set oFolder = oShell.BrowseForFolder(0, "Please select the folder where the files are located:", 1, Current)
    
    If (Not oFolder is Nothing) Then
        Set oFolderItem = oFolder.Self
        oPath = oFolderItem.Path
        
        If Right(oPath, 1) <> "\" Then
            oPath = oPath & "\"
        End If
    End If
    
    getFolder = oPath
   
End Function

machaz Thu, 09/28/2017 - 03:31

What exactly is the shell application and other uses can it have?
Is it documented anywhere in the language browser tool or how did you know about it, because I have been stressing on how to create such a dialog box.

klmi Tue, 07/07/2020 - 03:41

Hi Brian,
documentation has moved to the following links:
https://docs.microsoft.com/en-us/windows/win32/shell/shell-namespace
https://docs.microsoft.com/en-us/windows/win32/api/shldisp/ne-shldisp-s…
https://docs.microsoft.com/en-us/windows/win32/shell/shell-browseforfol…
 
Besides some further annotations to your code:
- String variable BrowseFolder is declared but not used ==> not necessary
- oPath suggests that the variable type is an Object but it is a String - so sPath maybe would be more clearly

Brian Element Tue, 07/07/2020 - 13:03

In reply to by klmi

Hi klmi, thanks for the update.  I wrote this almost 10 years ago, I guess some things change over time.