You can rename and move a specified file or folder using the built-in Name statement in VBA.
Rename a File or Folder
'----------------- Modules -----------------
Sub RenameFile()
Dim strPath As String
strPath = ThisWorkbook.Path & Application.PathSeparator
On Error GoTo errHandle
If Dir(strPath & "FolderA\Test.txt") <> "" Then
Name strPath & "FolderA\Test.txt" As strPath & "FolderA\Test1.txt"
Name strPath & "FolderA\Test1.txt" As strPath & "FolderA\FolderB\Test1.txt"
Name strPath & "FolderA\FolderB\Test1.txt" As strPath & "FolderA\Test.txt"
End If
Exit Sub
errHandle:
MsgBox Err.Description
End Sub
How This Macro Works
Line 7 code: renames "Test.txt" file to "Test1.txt".
Line 8 code: moves "Test1.txt" file from "FolderA\" to "FolderA\FolderB\".
Line 9 code: renames "Test1.txt" file to "Test.txt" and moves it from "FolderA\FolderB\" to "FolderA\".
Macro Download
How to Use This Macro
Most VBA code should be placed in Standard Modules unless specified.
If you see a comment '------------------ Modules------------------
in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?
The following steps teach you how to put VBA code into a Standard Module:
- Activate the Visual Basic Editor by pressing ALT + F11.
- Right-click the project/workbook name in the Project Window.
- Choose Insert -> Module.
- Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
- Click Run button on the Visual Basic Editor toolbar.
- For more information, learn this course: Programming with Excel VBA
Can I use this on renaming multiple files at once inside folders and subfolders?