Skip to main content

Excel Macro: Rename a File or Folder

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

Rename a File or Folder

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:

  1. Activate the Visual Basic Editor by pressing ALT + F11.
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert -> Module.
  4. 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.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Leave a comment

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

Format your code: <pre><code class="language-vba">place your code here</code></pre>

1 comment
  1. AM
    Amberle

    Can I use this on renaming multiple files at once inside folders and subfolders?