How to use RmDir statement in VBA?

In VBA (Visual Basic for Applications), the RmDir statement is used to delete an existing directory. It’s important to note that RmDir will only delete the directory if it is empty. If the directory contains files or subdirectories, you will need to delete them first before you can remove the directory. Here’s how to use the RmDir statement:

Basic Syntax

VBA
RmDir path
Here, path is a string expression that identifies the directory you want to delete. The path may include the drive.

Example Usage

VBA
RmDir "C:MyFolder"
This command would delete the directory named “MyFolder” located in the C drive.

Error Handling

It’s a good practice to include error handling when using RmDir, as attempting to remove a non-existent or non-empty directory will cause a run-time error. For example:
VBA
On Error Resume Next
RmDir "C:MyFolder"
If Err.Number <> 0 Then
    MsgBox "Error in deleting directory: " & Err.Description
End If
On Error GoTo 0
This code attempts to delete the specified directory and shows a message box if an error occurs.
  • Deleting Non-Empty Directories: As mentioned, RmDir can’t delete directories that contain files or other directories. To delete a non-empty directory, you would first need to recursively delete all its contents. This typically involves writing a custom function that deletes all files and subdirectories inside the directory before using RmDir.
  • Permissions and Access: Ensure that your VBA project has the necessary permissions to delete the directory, and that no files or subdirectories within it are open or being used by other applications.
  • Limitations: Remember that RmDir permanently deletes the directory without sending it to the Recycle Bin. There is no undo operation for RmDir, so use it with caution.
  • Network Drives and Paths: RmDir can also be used with network paths, assuming you have the necessary permissions and the network path is accessible.
Using RmDir can be powerful for managing file systems within VBA, but its irreversible nature means it should be used carefully and typically with user confirmation or adequate error handling.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project