Using Excel VBA to rename files in directory

samilynn

Board Regular
Joined
Jun 24, 2003
Messages
171
Office Version
  1. 2016
Platform
  1. Windows
is it possible to have a spreadsheet with two columns, Col A showing a list of current file names in a particular directory, and Col B the names I want these files to be renamed to. Is there some code that I can use to do this, or do I have to rename these files one by one until I get old? :(

Thanks,

Samantha
 

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
These are the macros I use.
ListFiles

FileNametoExcel
RenameFile


The important ones are FilenameToExcel (run this one first) and RenameFile (run this one second) after filling in the column with the new file name (you will see what I mean after you run FilenameToExcel).
The macro ListFiles just lists the files on a separate worksheet and is used for preping the filenames (for example using formulas to amend the file name in some way). I usually copy my amended file names and paste into the special range that is created by the macro FilenameToExcel.

I suggest you practice using these macros with a backup folder.



Code:
Option Explicit

'' ***************************************************************************
'' Purpose  : List selected files from a directory
'' Written  : 26-Feb-1999 by Andy Wiggins - Byg Software Ltd
''
' Two versions of this macro are shown here.
' The first version is the modified version which will parse the directories into separate columns
' The second version is the original version.
Sub ListFiles()
    
    Dim vvRes                   ''Variant to collect result
    Dim viLoopCounter%          ''For loop counter
    Dim CRCol As Integer
    Dim i As Integer
    Dim nWS As Worksheet
    Application.ScreenUpdating = False
    On Error GoTo Endit ' this is messy. The macro will add a sheet anyway and then delete it without asking. It works though.
    Set nWS = Worksheets.Add
    nWS.Cells.Activate
    ''Set an error trap - gets around a "Cancel" situation
    
    
    ''Clear the target range, column "A"
    Cells.Columns(1).ClearContents
    
    ''Go to the top left cell
    Cells(1, 1).Select
    
    ''Show the file open box and get a result
    vvRes = Application.GetOpenFilename("The lot, *.*", MultiSelect:=True)
    
    ''Loop for each result in the "fileToOpen" result ..
    For viLoopCounter = LBound(vvRes) To UBound(vvRes)
        
        '' ..  and input to a cell
        Cells(viLoopCounter, 1) = vvRes(viLoopCounter)
        
    Next
    
    
    Columns("A:A").Select
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
    Semicolon:=False, Comma:=False, Space:=False, other:=True, OtherChar _
    :="\", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, _
    1)), TrailingMinusNumbers:=True
    Cells.Select
    Selection.Columns.AutoFit
    Do While Range("A1").Value = ""
        Columns(1).EntireColumn.Delete
    Loop
    Range("A1").Select
    CRCol = Selection.CurrentRegion.Columns.Count
    For i = 1 To CRCol - 2
        
        Columns(1).EntireColumn.Delete
        
    Next i
    Range("A1").EntireRow.Insert
    Range("A1").Select
    With Selection
        .Value = "Folder"
        .Font.FontStyle = "Bold"
    End With
    Range("B1").Select
    With Selection
        .Value = "Filename"
        .Font.FontStyle = "Bold"
    End With
    On Error Resume Next
    nWS.Name = Range("A2").Value
    GoTo Finish ' the macro has run with no errors
Endit:     ' perhaps someone cancelled half-way, but a sheet has been added anyway. The section deletes that sheet.
    Application.DisplayAlerts = False
    ActiveSheet.Delete
    Application.DisplayAlerts = True
Finish:
End Sub
Sub FileNametoExcel()
    
    Dim fnam As Variant
    ' fnam is an array of files returned from GetOpenFileName
    ' note that fnam is of type boolean if no array is returned.
    ' That is, if the user clicks on cancel in the file open dialog box, fnam is set to FALSE
    
    Dim b As Integer 'counter for filname array
    Dim b1 As Integer 'counter for finding \ in filename
    Dim c As Integer 'extention marker
    
    ' format header
    Range("A1").Select
    ActiveCell.FormulaR1C1 = "Path and Filenames that had been selected to Rename"
    Range("A1").Select
    With Selection.Font
        .Name = "Arial"
        .FontStyle = "Bold"
        .Size = 10
    End With
    Columns("A:A").EntireColumn.AutoFit
    Range("B1").Select
    ActiveCell.FormulaR1C1 = "Input New Filenames Below"
    Range("B1").Select
    With Selection.Font
        .Name = "Arial"
        .FontStyle = "Bold"
        .Size = 10
    End With
    Columns("B:B").EntireColumn.AutoFit
    
    ' first open a blank sheet and go to top left  ActiveWorkbook.Worksheets.Add
    
    fnam = Application.GetOpenFilename("all files (*.*), *.*", 1, _
    "Select Files to Fill Range", "Get Data", True)
    
    If TypeName(fnam) = "Boolean" And Not (IsArray(fnam)) Then Exit Sub
    
    'if user hits cancel, then end
    
    For b = 1 To UBound(fnam)
        ' print out the filename (with path) into first column of new sheet
        ActiveSheet.Cells(b + 1, 1) = fnam(b)
    Next
    
    
End Sub


Sub RenameFile()
    Dim z As String
    Dim s As String
    Dim V As Integer
    Dim TotalRow As Integer
    
    TotalRow = ActiveSheet.UsedRange.Rows.Count
    
    For V = 1 To TotalRow
        
        ' Get value of each row in columns 1 start at row 2
        z = Cells(V + 1, 1).Value
        ' Get value of each row in columns 2 start at row 2
        s = Cells(V + 1, 2).Value
        
        Dim sOldPathName As String
        sOldPathName = z
        On Error Resume Next
        Name sOldPathName As s
        
    Next V
    
    MsgBox "Congratulations! You have successfully renamed all the files"
    
End Sub

Hi.
Is there way to make this work with subfolders too? As in collect all the files in given folder and subfolders under it.?
 
Upvote 0
Hello!
I have used your example with success!
However, can I add code to insert a password from a pre-determined list that is on the same sheet as the naming convention is saved ... they are in column 6 and are set for each of the names through an index.

thanx!
 
Upvote 0
i encounter run-time error '53' file not found when execute rename_files().When i click debug,it link me to

Name Cells(r,"A") As Cells(r,"B")

Thanks to jfarc the code works and the reason you are getting the run-time error is that the code is missing the file the path. Add the path and follow the instructions provided by jfarc and it will do the job - see the updated line of code as shown below:

Cells(a, 1).Value = MyFolder & MyFile

Hope this helps.
 
Upvote 0
jfarc code posted on Oct 19th, 2009, 07:05 AM works fine and is an easy way to rename files. The reason imskin is running to a runtime error as posted on Jul 28th, 2013, 07:45 PM is the code is missing the path. Add the path to the cell value and follow the instruction jfarc provided and it will nicely rename the files. See the updated code below:

Cells(a, 1).Value = MyFolder & MyFile

Hope this helps.
 
Upvote 0
This is the most beautiful thing I ve ever seen over a decade


Sorry about the delay. I was really busy and never got back to this post.

I have tried to simplify the process.

Here is a link to a video which illustrates:
https://drive.google.com/file/d/0B8zDl6Y-moiIR3YzTXRRNGh2X1U/view?usp=sharing

You will need to download the video if you wish to watch it. The video is silent but I hope you can follow along.

Part 1. Lists the files you wish to rename. Use this as a starting point for modifying the file names using whichever method you prefer. In the video I use a formula
Code:
Sub RenameFiles_Part1()
    ' List the file names
    ' after the files have been listed modify the file names
    ' And then run Part 2 which lists the full path of the files to be renamed
    ' copy the modified file names to column B of the worksheet "temp_RenameFiles"
    ' And then run part 3, which will rename the files


    Application.DisplayAlerts = False
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = Worksheets("temp_FileList")
    If Not ws Is Nothing Then
        ws.Delete
    End If
    On Error GoTo 0
    Set ws = Worksheets.Add(Before:=ActiveSheet)
    ws.Name = "temp_FileList"
    ws.Activate
    Application.DisplayAlerts = False


    Dim fd As FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    Dim FileChosen As Integer, i As Long
    Dim MyFile As Variant
    i = 1
    fd.AllowMultiSelect = True
    fd.Show
    For Each MyFile In fd.SelectedItems
        ws.Cells(i, 1).Value = StrReverse(Mid(StrReverse(MyFile), 1, InStr(StrReverse(MyFile), "\") - 1))
        i = i + 1
    Next MyFile
    
End Sub

Part 2: Inserts another worksheet this time listing the files with the full path. In column B you enter the new file names.
Code:
Sub RenameFiles_Part2()
    ' List the full path of the files to be renamed
    Application.DisplayAlerts = False
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = Worksheets("temp_RenameFiles")
    If Not ws Is Nothing Then
        ws.Delete
    End If
    On Error GoTo 0
    Set ws = Worksheets.Add(Before:=ActiveSheet)
    ws.Name = "temp_RenameFiles"
    ws.Activate
    
    Application.DisplayAlerts = True


    Dim fnam As Variant


    Dim b As Integer 'counter for filname array
    Dim b1 As Integer 'counter for finding \ in filename
    Dim c As Integer 'extention marker


    ' format header
    With ws
        .Range("A1").Value = "Path and Filenames that had been selected to Rename"
        .Range("B1").Value = "Input New Filenames Below"
    End With
    
    With ws.Range("A1:B1")
        .Font.Name = "Arial"
        .Font.FontStyle = "Bold"
        .Font.Size = 10
    End With


    ' first open a blank sheet and go to top left  ActiveWorkbook.Worksheets.Add
 
    fnam = Application.GetOpenFilename("all files (*.*), *.*", 1, _
    "Select Files to Fill Range", "Get Data", True)


      If TypeName(fnam) = "Boolean" And Not (IsArray(fnam)) Then Exit Sub
    
      For b = 1 To UBound(fnam)
         ' print out the filename (with path) into first column of new sheet
         ws.Cells(b + 1, 1) = fnam(b)
      Next
          
    ws.Range("A:B").EntireColumn.AutoFit


End Sub

Part 3: The last macro actually renames the files.
Code:
Sub RenameFiles_Part3()
    ' Rename the Files
    Dim z As String
    Dim S As String
    Dim v As Integer
    Dim TotalRow As Integer
    
    TotalRow = ActiveSheet.UsedRange.Rows.Count
    
    For v = 1 To TotalRow
    
    ' Get value of each row in columns 1 start at row 2
    z = Cells(v + 1, 1).Value
    ' Get value of each row in columns 2 start at row 2
    S = Cells(v + 1, 2).Value
    
      Dim sOldPathName As String
      sOldPathName = z
      On Error Resume Next
      Name sOldPathName As S
      
    Next v
    
    MsgBox "Congratulations! You have successfully renamed all the files"


End Sub

I hope this helps anyone who stumbles upon this thread.
 
Upvote 0
Make two buttons, one for data upload , 2nd for renaming

for data upload into your spread sheet directly, so that you may get a relief of typing, use

Dim fnam As Variant
' fnam is an array of files returned from GetOpenFileName
' note that fnam is of type boolean if no array is returned.
' That is, if the user clicks on cancel in the file open dialog box, fnam is set to FALSE
Range("A:F").ClearContents
Dim b As Integer 'counter for filname array
Dim b1 As Integer 'counter for finding \ in filename
Dim c As Integer 'extention marker

' format header
Range("A1").Select
ActiveCell.FormulaR1C1 = "Path and Filenames ( Old )"
Range("A1").Select
With Selection.Font
.Name = "Arial"
.FontStyle = "Bold"
.Size = 10
End With
Columns("A:A").EntireColumn.AutoFit
Range("c1").Select
ActiveCell.FormulaR1C1 = "Path and Filenames ( New )"
Range("c1").Select
With Selection.Font
.Name = "Arial"
.FontStyle = "Bold"
.Size = 10
End With
Columns("b:b").EntireColumn.AutoFit
Range("b1").Select
ActiveCell.FormulaR1C1 = "Input New Filenames Below"
Range("b1").Select
With Selection.Font
.Name = "Arial"
.FontStyle = "Bold"
.Size = 10
End With
Columns("b:b").EntireColumn.AutoFit

' first open a blank sheet and go to top left ActiveWorkbook.Worksheets.Add

fnam = Application.GetOpenFilename("all files (*.*), *.*", 1, _
"Select Files to Fill Range", "Get Data", True)

If TypeName(fnam) = "Boolean" And Not (IsArray(fnam)) Then Exit Sub

'if user hits cancel, then end

For b = 1 To UBound(fnam)
' print out the filename (with path) into first column of new sheet
ActiveSheet.Cells(b + 1, 1) = fnam(b)
Next
 
Upvote 0
i encounter run-time error '53' file not found when execute rename_files().When i click debug,it link me to

Name Cells(r,"A") As Cells(r,"B")

jfarc's code is fairly efficient. He simply forgot to add the folder location in front of the file names. That's why you got an error.

Simply replace
VBA Code:
Name  Cells(r, "A") As  Cells(r, "B")

with the following code:
Code:
Name "C:\your_folder_name\" & Cells(r, "A") As "C:\your_folder_name\" & Cells(r, "B")
 
Upvote 0
Hello,

I know I am many years late but if anyone stumbles this low they may end needing the same thing as me :)

In my case I needed to copy a file, change the name, and paste it into a different folder.

I have about 6300 files to do this with, automation is required. The only thing this code does not have is the loop which is really easy to add.

You can see the end results in the image below:

1648738722184.png


Sub CopyFiles()

Dim FSO As Object
Dim SourceFileName As String, DestinFileName As String

Worksheets("Sheet1").Select

Set FSO = CreateObject("Scripting.Filesystemobject")
SourceFileName = Cells(1, 3).Value & "\" & Cells(1, 1).Value & ".txt" 'Example: "C:\Users\Jun.xlsx"
DestinFileName = Cells(1, 4).Value & "\" & Cells(1, 2).Value & ".txt" 'Example: "C:\Users\Desktop\Jun.xlsx"

FSO.CopyFile Source:=SourceFileName, Destination:=DestinFileName

MsgBox (SourceFileName + " Moved to " + DestinFileName)


End Sub
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,022
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top