How to Get Folder or Select Folder
In this How To, I will show you how to create a function to get folder and assign to a textbox field. I have a function given below that will return the folder name with its path. In the function below there is no parameter for the input. You can set it as a Sup Procedure like code below.
Full Code:
Function SelectFolder() ‘or Sub SelectFolder()
Dim Fd As FileDialog
Set Fd = Application.FileDialog(msoFileDialogFolderPicker)
With Fd
.AllowMultiSelect = False
.Title = "Please select folder"
If .Show = True Then 'if OK is pressed
Me.BackupFolder = .SelectedItems(1) 'write the selected folder in the textbox
Else
Exit Function 'click Cancel or X box to close the dialog
End If
End With
Set Fd = Nothing
End Function ‘End Sub
Explanation:
- FileDialog(msoFileDialogFolderPicker) ‘Open the file dialog allowing the user to select folder.
- With Fd ‘Use With statement to avoid type Fd in front of every property
- .AllowMultiSelect = False ‘ Allow to select only one folder
- .Title ‘Set Title on popup window
- .Show = True ‘If OK is pressed on the dialog window
- Me.BackupFolder = .SelectedItems(1) ‘write the selected folder in the textbox
Apply Function
In the picture below, I have a textbox name “Backupfolder” that is bounded to the BackupFolder field in the table.
Call the SelectFolder() function under the On Click Event of the button next to textbox.
The dialog window will open after clicking on the button above. The user will browse to and select the folder. The selected folder will display on the Backupfolder textbox after clicking OK button (from code: If .Show = True Then Me.BackupFolder = .SelectedItems(1)).