In many applications or tools you will build with Excel VBA, you will often come across a need to browse a folder. One way of getting the folder is accepting it in a cell in sheet from the user. Another, also elegant, way of doing that is to open a File Dialog and let user pick the folder dynamically. The following code should serve your purpose
Sub BrowseFolder()
On Error GoTo ErrorHandler
Dim oFldr As FileDialog
Dim sItem As String
'Set the FileDialog object to Folder Picker
Set oFldr = Application.FileDialog(msoFileDialogFolderPicker)
'The Title which appears on the dialog
oFldr.Title = "Select a Folder"
'Multiselect Option on the dialog
oFldr.AllowMultiSelect = False
'Initial Path from where the dialog needs to start
oFldr.InitialFileName = "C:\"
If oFldr.Show <> -1 Then
GoTo ErrorHandler
Else
sItem = oFldr.SelectedItems(1)
MsgBox (sItem)
End If
ErrorHandler:
End Sub
On Error GoTo ErrorHandler
Dim oFldr As FileDialog
Dim sItem As String
'Set the FileDialog object to Folder Picker
Set oFldr = Application.FileDialog(msoFileDialogFolderPicker)
'The Title which appears on the dialog
oFldr.Title = "Select a Folder"
'Multiselect Option on the dialog
oFldr.AllowMultiSelect = False
'Initial Path from where the dialog needs to start
oFldr.InitialFileName = "C:\"
If oFldr.Show <> -1 Then
GoTo ErrorHandler
Else
sItem = oFldr.SelectedItems(1)
MsgBox (sItem)
End If
ErrorHandler:
End Sub
You can also download the sample code here.
The code is pretty straight forward with imbeded comments for explainations. Please feel free to ask any questions or issues you face using the above.
0 comments:
Post a Comment