How to use ChDrive statement in VBA?

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
ChDrive drive
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”).

Examples

To change to the D drive:
VBA
ChDrive "D"
or
VBA
ChDrive "D:"
To change to the C drive:
VBA
ChDrive "C"
or
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
On Error Resume Next
ChDrive "Z"
If Err.Number <> 0 Then
    MsgBox "Drive not found!"
    Err.Clear
End If
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.

Switch the language

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project