The ChDir statement in VBA (Visual Basic for Applications) is used to change the current directory or folder. Here’s how you can use it:
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.
Change to a specific directory:
This would change the current directory to C:\Documents.
Change to a directory on a different drive:
This would change the current directory to D:\Data on the D: drive.
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.
It’s good practice to include error handling when changing directories, especially if the path might not exist or could vary. For example:
On Error Resume Next
If Err.Number <> 0 Then
MsgBox "Directory not found!"
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.