Using common dialog to select directories
By: Tom Kumpf Date: 24/09/1998

You may have an occasion to want to use the common dialog box as a directory-picker instead of creating a separate form and placing a directory control on it.

'Initialize Common Dialog control
With cdMain
   .Flags = cdlOFNPathMustExist
   .Flags = .Flags Or cdlOFNHideReadOnly
   .Flags = .Flags Or cdlOFNNoChangeDir
   .Flags = .Flags Or cdlOFNExplorer
   .Flags = .Flags Or cdlOFNNoValidate
   .filename = "*.*"
End With

The cdlOFNNoValidate seting permits the user to press "Open" while no single file is selected. The filename setting of "*.*" now satisfies the common dialog.

To parse the directory, use the following logic from where you present the dialog:

Private Sub btnBrowse_Click()
    Dim x As Integer
    'Cheap way to use the common dialog box as a directory-picker
    x = 3

    cdMain.CancelError = True    'Do not terminate on error

    On Error Resume Next         'I will hande errors

    cdMain.Action = 1            'Present "open" dialog

    'If FileTitle is null, user did not override the default (*.*)
    If cdMain.FileTitle <> "" Then x = Len(cdMain.FileTitle)

    If Err = 0 Then
        ChDrive cdMain.filename
        txtPath.Text = Left(cdMain.filename, Len(cdMain.filename) - x)
    Else
        'User pressed "Cancel"
    End If

End Sub

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
Webmaster's e-mail: webmaster@vbprogzone.cjb.net
Hosted by InWind: www.inwind.it