
Syntax
VBA
Name oldPath As newPath
- oldPath: The current name and location of the file. This must include the full path if the file is not in the current directory.
- newPath: The new name and/or location for the file. This also must include the full path if the file is not in the current directory.
How to Use
Renaming a File
To rename a file, you provide the current file path and name, and the new name you want for the file.VBA
This will rename “OldFileName.txt” to “NewFileName.txt” in the “MyFolder” directory.
Name "C:MyFolderOldFileName.txt" As "C:MyFolderNewFileName.txt"
Moving a File
You can also use the Name statement to move a file from one directory to another.VBA
This moves “MyFile.txt” from “MyFolder” to “AnotherFolder”.
Name "C:MyFolderMyFile.txt" As "C:AnotherFolderMyFile.txt"
Error Handling
It’s important to include error handling, as attempting to rename or move a file that does not exist, or if there are permission issues, will result in a runtime error.VBA
On Error Resume Next
Name "C:MyFolderOldFileName.txt" As "C:MyFolderNewFileName.txt"
If Err.Number <> 0 Then
MsgBox "Error in renaming/moving file: " & Err.Description
End If
On Error GoTo 0
Important Considerations
- File Existence: The file specified by oldPath must exist, or an error will occur.
- File Overwriting: If a file with the name specified by newPath already exists, an error will occur. VBA’s Name statement does not overwrite existing files.
- Permissions: The user running the VBA script must have adequate permissions to rename or move the file.
- Open Files: If the file is open in another application, an error will occur. Ensure the file is closed before attempting to rename or move it.
- File Extension Change: Be cautious when changing file extensions, as this might render the file unusable or unrecognizable by other applications.