To RENAME an Excel file that is stored on your computer, you need to use the “NAME” statement. In this statement, you need to define the old file name and the new name that you want to apply. But there’s one thing that you need to remember that the file must be closed.
Here I have an Excel file that is stored in the “Data” folder on my desktop and there in this folder “SampleFile” that I want to rename to the “myFile” and code for this would be like the following.
Name "C:\Users\Dell\Desktop\myFolder\SampleFile.xlsx" As _ "C:\Users\Dell\Desktop\myFolder\myNewFile.xlsx"
Steps to use VBA to Rename Excel File
Now, let’s understand this line of code in detail.
- The name statement with which you need to start the code.
- Address of the file with the old name and file extension.
- “As” to refer to the new name.
- Address of the file with the new name and file extension.
To make the name statement a little clearer you can use variables, just like the following code.
Sub vba_rename_workbook() Dim oldName As String Dim newName As String oldName = "C:\Users\Dell\Desktop\myFolder\SampleFile.xlsx" newName = "C:\Users\Dell\Desktop\myFolder\myNewFile.xlsx" Name oldName As newName End Sub
More on VBA Workbooks
VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)