Introduction
I was creating a VBA program to create a folder and save Excel files inside it. Initially, I fixed the folder path directly in the code. However, I realized that the destination folder might change each time I run the program.
To solve this, I learned how to use a dialog box that allows the user to select the destination folder manually.
Solution: Using a Dialog Box
VBA provides a specific feature to display a dialog box for selecting folders: Application.FileDialog(msoFileDialogFolderPicker).
Code Example
Sub SelectFolderUsingDialog()
Dim SelectFolder As String
' Set up the folder selection dialog
With Application.FileDialog(msoFileDialogFolderPicker)
' If the user clicks "OK", .Show returns True
If .Show = True Then
' Get the path of the selected folder
SelectFolder = .SelectedItems(1)
MsgBox "The selected folder is: " & SelectFolder
End If
End With
End Sub
Code Explanation
Dim SelectFolder As StringDeclares a string variable to store the path of the selected folder.With Application.FileDialog(msoFileDialogFolderPicker)Configures the settings for the folder picker dialog.If .Show = True ThenDisplays the dialog box. If the user selects a folder and clicks “OK”,.ShowreturnsTrue. If they click “Cancel”, it returnsFalse.SelectFolder = .SelectedItems(1)Retrieves the full path of the folder selected by the user.
Next Steps
By using this dialog box feature, users can freely choose the destination folder every time.
In practice, you can expand this code to create a more useful tool by combining it with logic to create new folders or save Excel files to the selected path.
Summary
In this article, I explained how to select a destination folder using a dialog box.
Using Application.FileDialog(msoFileDialogFolderPicker) significantly improves the usability of your tool by allowing flexible folder selection. FileDialog also has arguments for other purposes (like selecting files), so I plan to learn how to use those depending on the situation.
