How to Rename a File Using VBA (With Example)

You can use the Name statement in VBA to rename an Excel file.

Here is one common way to use this statement in practice:

Sub RenameFile()

Name "C:\Users\bob\Documents\current_data\my_old_file.xlsx" As _

End Sub

This particular macro will rename the file called my_old_file.xlsx to be called my_new_file.xlsx.

Note: You could write both file paths on the same line but we used an underscore ( _ ) to continue the code on the next line to make it easier to read.

The following example shows how to use this syntax in practice.

Example: Rename a File Using VBA

Suppose we have a folder located in the following location:


This folder contains three Excel files:

Suppose we would like to use VBA to rename the file called soccer_data.xlsx to be soccer_data_new.xlsx instead.

We can create the following macro to do so:

Sub RenameFile()

Name "C:\Users\bob\Documents\current_data\soccer_data.xlsx" As _

End Sub

Once we run this macro, the file that we specified will be renamed.

We can navigate to the folder location and check to see that soccer_data.xlsx has been renamed to soccer_data_new_.xlsx:

We can see that the file has indeed been renamed and all other files in the folder have remained unchanged.

Note: You can find the complete documentation for the Name statement in VBA here.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

How to Create Folders Using VBA
How to Delete Folders Using VBA
How to Delete Files Using VBA
How to Check if File Exists Using VBA

Leave a Reply

Your email address will not be published. Required fields are marked *