VBScript - Select a Folder

Have you ever wanted to use the browse for a folder dialog box from your VBScript?  Well maybe you can make use of this function?  It’s an amalgamation of various other scripts tailored to my own needs so hopefully it’ll suit your purposes too, but if not just tweak it until it does.

Option Explicit

Function SelectFolder(pstrDialogLabel)
    'Select a folder
    Const BIF_returnonlyfsdirs   = &H0001
    Const BIF_editbox            = &H0010

    Dim objBrowseFolderDialog, objFolder, objFSO, objSelection
    Dim bBrowseForFolder

    Set objBrowseFolderDialog = WScript.CreateObject("Shell.Application")

    bBrowseForFolder = true

    While bBrowseForFolder
        Set objFolder = objBrowseFolderDialog.BrowseForFolder (&H0, pstrDialogLabel, BIF_editbox + BIF_returnonlyfsdirs)

        'Check that something has been returned
        If IsValidFolder(objFolder) Then
            Set objFSO = CreateObject("Scripting.FileSystemObject")

            Set objSelection = objFolder.Self
            If objFSO.FolderExists(objSelection.Path) Then
                'A valid folder has been selected
                SelectFolder = objSelection.Path
                bBrowseForFolder = false
            Else
                'The selection is not a valid folder, try again...
                MsgBox objFolder.Title & " is not a valid folder, please select another folder" _
                    , vbOKOnly & vbExclamation, "Invalid Selection"
            End If
        Else
            'Nothing was selected, so return a null string
            SelectFolder = ""
            bBrowseForFolder = false
        End If
    Wend
End Function

Function IsValidFolder(pobjFolder)
    'Check that we have a valid value
    'i.e. you can concatenate it to a string
    Dim strTest

    On Error Resume Next

    strTest = " " & pobjFolder

    If Err <> 0 Then
        IsValidFolder = false
    Else
        IsValidFolder = true
    End If

    On Error GoTo 0
End Function

To use it simply pass the function a bit of text that you would like to display at the top of the browse dialog box and the function will then return the path to the folder.  The function will force the user to select a folder item with a “proper” path so items such as ‘My Computer’ and ‘My Network Places’ will prompt the user to reselect a folder item.  Should the user cancel then an empty string will be returned by the function.

An example call might look like:

MsgBox SelectFolder("Please select a folder")
Author: Stephen Millard
Tags: | vbs |

Buy me a coffeeBuy me a coffee



Related posts that you may also like to read