When using a dialog box to select files in VBA, it can be very tedious to manually navigate to deep folder hierarchies if the initial folder is not set correctly.
This article explains how to specify the folder that appears first when a dialog box is opened.
Solution: Using “ChDrive” and “ChDir”
To change the initial default folder, use the VBA statements ChDrive and ChDir before opening the dialog.
Sample Code
Sub SetInitialDirectory()
' 1. Change the current drive (e.g., "C")
ChDrive "C"
' 2. Change the current directory to the specific path
' Note: Ensure this path exists on your machine
ChDir "C:\Users\mori\Desktop\VBA\Study\"
' Example: When you open a file dialog after this, it starts in the folder above
' Application.GetOpenFilename
End Sub
Code Explanation
ChDrive "C": Changes the current drive to the “C drive”.ChDir "C:\Users\...": Moves the current directory to the specified path.
By executing these commands, the file selection dialog will open directly in this specified folder.
Note: In VBA code, paths are separated by the Backslash (\).
Important Notes
- Path Validity: Always specify a folder that actually exists. Specifying a non-existent path will result in an error.
- Drive Switching: If the target folder is on a different drive than the current one (e.g., moving from C: to D:), you must use
ChDriveto switch drives.ChDiralone only changes the folder within the current drive.
Summary
To specify the initial folder for a file selection dialog in VBA:
- Specify the drive using
ChDrive. - Specify the folder path using
ChDir.
This simple setup can significantly improve your workflow efficiency.
