How to Rename a file with Excel VBA?
To rename a file with VBA, use the function mentioned below. Usually, You can find a lot of function used in VBA under the object 'VBA'. But, this vba rename file is one of those few functions that exists outside of 'VBA' object & it can be used directly as mentioned below:- Function Name: Name
- Syntax: Name [OldName] As [NewName]
Excel VBA Rename file without Opening file
From any Excel workbook, press Alt F11 to view the VB editor. Then copy paste the below code & change the example file name to a file that exists in your computer.Sub ExcelVBARenameFileName()
Dim sExistingFileName As String
Dim sRenamedTo As String
'File to be renamed
sExistingFileName = "D:\Filename1.txt"
'New Name for the file
sRenamedTo = "D:\Filename2.txt"
'VBA command to Rename file
Name sExistingFileName As sRenamedTo
End Sub
You cannot run this code twice. Because the old file will not exist after the first run.
This code will give error if the source file is not found in the path. So, it is better to have a VBA.Dir command to check if the file exists, then perform the rename operation.
So, press F5 only once to check this code.