[VBA] How to Set the Initial Folder for File Dialog Boxes (ChDrive and ChDir)

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

  1. Path Validity: Always specify a folder that actually exists. Specifying a non-existent path will result in an error.
  2. 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 ChDrive to switch drives. ChDir alone only changes the folder within the current drive.

Summary

To specify the initial folder for a file selection dialog in VBA:

  1. Specify the drive using ChDrive.
  2. Specify the folder path using ChDir.

This simple setup can significantly improve your workflow efficiency.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次