
Syntax
VBA
path is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.
ChDir path
Examples
Change to a specific directory:VBA
This would change the current directory to C:Documents.
Change to a directory on a different drive:
ChDir "C:Documents"
VBA
This would change the current directory to D:Data on the D: drive.
ChDir "D:Data"
Points to Note
- The specified path must exist; otherwise, an error occurs.
- If you are changing the directory on a drive other than the current drive, you need to explicitly change the drive using the ChDrive statement before using ChDir.
- ChDir doesn’t create a new directory. Use MkDir statement to create a new directory.
Error Handling
It’s good practice to include error handling when changing directories, especially if the path might not exist or could vary. For example:VBA
Remember, ChDir affects all file-handling functions that do not include a path as part of the file name. After running a ChDir statement, any files opened without a full path will be opened in the new directory.
On Error Resume Next
ChDir "C:UnknownFolder"
If Err.Number <> 0 Then
MsgBox "Directory not found!"
Err.Clear
End If