The ChDrive statement in VBA (Visual Basic for Applications) is used to change the current drive. It’s a simple and straightforward statement, but it’s important to remember that it only changes the drive, not the directory. Here’s how to use it
Syntax
VBA
Here, drive is a string expression that specifies the new drive. It can be a letter followed by a colon (e.g., “C:”) or just the letter (e.g., “C”).
ChDrive drive
Examples
To change to the D drive:VBA
or
ChDrive "D"
VBA
To change to the C drive:
ChDrive "D:"
VBA
or
ChDrive "C"
VBA
ChDrive "C:"
Points to Note
- The drive you are trying to change to must exist; otherwise, an error will occur.
- If you want to change both the drive and the directory, you must use ChDrive to change the drive and ChDir to change the directory.
- ChDrive is particularly useful when working with file paths on different drives.
Error Handling
As with any file operation, it’s good practice to include error handling. For example:VBA
This statement is especially useful in scenarios where your VBA code needs to work with files across multiple drives, and you need to programmatically switch between them.
On Error Resume Next
ChDrive "Z"
If Err.Number <> 0 Then
MsgBox "Drive not found!"
Err.Clear
End If