Browse for folders code to select folders

sujittalukde

Well-known Member
Joined
Jun 2, 2007
Messages
520
I am using the following code to select the folder path:
Code:
Sub x()
    Dim xx
    xx = Application.FileDialog(msoFileDialogFolderPicker).Show
    MsgBox CurDir
End Sub

The code has two pitfalls which I need to fix:
1. If the "Cancel" button is cancelled, then also it is giving the path.
2. I want that user must select a folder ie this code gives output if onlu Drive is selected as C:\. I want that if only drive is selected then it should give a message that only drive is selected and must select o folder.

How can I do so?
 

Excel Facts

Fastest way to copy a worksheet?
Hold down the Ctrl key while dragging tab for Sheet1 to the right. Excel will make a copy of the worksheet.
Try:-
Code:
Dim CurDir As String
 
CurDir = ""
 
Do Until CurDir <> ""
  With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Please choose a folder:-"
    .AllowMultiSelect = False
    If .Show = -1 Then CurDir = .SelectedItems(1)
  End With
  If CurDir = "" Then
    MsgBox "You hit 'Cancel' - no folder selected", vbOKOnly + vbExclamation
    Exit Do
  End If
  If Len(CurDir) = 3 Then
    MsgBox "You may not select a root folder: please try again.", vbOKOnly + vbExclamation
    CurDir = ""
  End If
Loop
 
Upvote 0
Yeah, I found it.
Before the Loop I ahve added the line:
If Len(CurDir) > 3 Then
MsgBox CurDir
End If

Is this correct approach?
 
Upvote 0
When the program drops out of the loop, CurDir is either blank or else it has a valid path in it, so you do If CurDir = "" Then take whatever action you want if it's blank Else you take whatever action you want if it's valid.
 
Upvote 0

Forum statistics

Threads
1,224,575
Messages
6,179,637
Members
452,934
Latest member
Jdsonne31

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top