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
 
As that is a different task from renaming files, may I suggest you make a new thread, with a descriptive subject title. For example, Excel VBA - Copy files from one folder to another.

Hi All,

Need a suggestion on renaming Multiple files...

My excel has 2 parts, 1st for input image names and 2nd for output image name. Say 8 columns for input file names and same for output and each raw belongs to one item.
Example Raw 1: ABC, BCD,CDE,DEF,EFG,FGH,GHI,HIJ

I need an output renamed image: xyz, xyz_1, xyz_2, xyz_3, xyz_4, xyz_5, xyz_6, xyz_7

I got your VB code for 1 column input and 1 Column output. How do I get this done with multiple columns.

Would be very grateful if someone could suggest something on it.

Rgds
Manish
 
Upvote 0

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).
Hi All,

Need a suggestion on renaming Multiple files...

My excel has 2 parts, 1st for input image names and 2nd for output image name. Say 8 columns for input file names and same for output and each raw belongs to one item.
Example Raw 1: ABC, BCD,CDE,DEF,EFG,FGH,GHI,HIJ

I need an output renamed image: xyz, xyz_1, xyz_2, xyz_3, xyz_4, xyz_5, xyz_6, xyz_7

I got your VB code for 1 column input and 1 Column output. How do I get this done with multiple columns.

Would be very grateful if someone could suggest something on it.

Rgds
Manish

Hi Manish

Not sure if I understand. The macro is used to rename file in a directory. Why do you need multiple columns? I can't see where that comes into it.
If you are renaming files using code then it really needs to know two things: old name, new name. Hence two columns.

What is the purpose you have in mind for more than two columns columns? For example, why do you want to list the input file names across 8 columns?
 
Upvote 0
Hi Manish

Not sure if I understand. The macro is used to rename file in a directory. Why do you need multiple columns? I can't see where that comes into it.
If you are renaming files using code then it really needs to know two things: old name, new name. Hence two columns.

What is the purpose you have in mind for more than two columns columns? For example, why do you want to list the input file names across 8 columns?

Hi There,

First of all - Thank you for your reply on it.

Let me explain the need...

[TABLE="width: 1196"]
<colgroup><col><col><col><col><col span="5"><col><col><col><col><col><col></colgroup><tbody>[TR]
[TD] [/TD]
[TD] [/TD]
[TD]Input[/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD] [/TD]
[TD]Output[/TD]
[TD] [/TD]
[TD] [/TD]
[/TR]
[TR]
[TD] [/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD] [/TD]
[TD][/TD]
[TD][/TD]
[TD="colspan: 2"] (Auto Generated)[/TD]
[TD][/TD]
[/TR]
[TR]
[TD]Item Nmae[/TD]
[TD]Main Img[/TD]
[TD]_1[/TD]
[TD]_2[/TD]
[TD]_3[/TD]
[TD]_4[/TD]
[TD]_5[/TD]
[TD]_6[/TD]
[TD]_7[/TD]
[TD] [/TD]
[TD]Main Image 1[/TD]
[TD]Img 2[/TD]
[TD]Img 3[/TD]
[TD]Img 4[/TD]
[TD]Img 5[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
</tbody>[/TABLE]

It would have 1 item name and there may be say 2-5 images of every item as original camera names.

What I want is that every Item should have it's images as Item, Item_1`, Item_2, Item_3 to recognize by name which image belongs to which item.

I did try to convert with a .bat file but didn't work. I totally understand a code will need 2 columns and for that can you suggest me something how to paste these items somehow that it may only have 2 columns and without blank spaces which should have exact image name in front of it...

Hope I could explain.. If not please reply back..

Rgds
Mannn
 
Upvote 0
Hi There,

First of all - Thank you for your reply on it.

Let me explain the need...

[TABLE="width: 1196"]
<tbody>[TR]
[TD][/TD]
[TD][/TD]
[TD]Input[/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD]Output[/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD="colspan: 2"] (Auto Generated)[/TD]
[TD][/TD]
[/TR]
[TR]
[TD]Item Nmae[/TD]
[TD]Main Img[/TD]
[TD]_1[/TD]
[TD]_2[/TD]
[TD]_3[/TD]
[TD]_4[/TD]
[TD]_5[/TD]
[TD]_6[/TD]
[TD]_7[/TD]
[TD][/TD]
[TD]Main Image 1[/TD]
[TD]Img 2[/TD]
[TD]Img 3[/TD]
[TD]Img 4[/TD]
[TD]Img 5[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
</tbody>[/TABLE]

It would have 1 item name and there may be say 2-5 images of every item as original camera names.

What I want is that every Item should have it's images as Item, Item_1`, Item_2, Item_3 to recognize by name which image belongs to which item.

I did try to convert with a .bat file but didn't work. I totally understand a code will need 2 columns and for that can you suggest me something how to paste these items somehow that it may only have 2 columns and without blank spaces which should have exact image name in front of it...

Hope I could explain.. If not please reply back..

Rgds
Mannn



Hi There,

As per your directions, I have managed to pull the above data into just 2 columns. 1 being Input and other being output in a new Tab of the same excel.

However it contains empty cells in between.

Actual Example:
[TABLE="width: 443"]
<colgroup><col><col><col></colgroup><tbody>[TR]
[TD]Input[/TD]
[TD] [/TD]
[TD]Output[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]DSC_0133[/TD]
[TD][/TD]
[TD]ren DSC_0133.JPG SP002.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0138[/TD]
[TD][/TD]
[TD]ren DSC_0138.JPG SP003.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0139[/TD]
[TD][/TD]
[TD]ren DSC_0139.JPG SP004.JPG[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]DSC_0150[/TD]
[TD][/TD]
[TD]ren DSC_0150.JPG SP007.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0151[/TD]
[TD][/TD]
[TD]ren DSC_0151.JPG SP008.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0152[/TD]
[TD][/TD]
[TD]ren DSC_0152.JPG SP009.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0153[/TD]
[TD][/TD]
[TD]ren DSC_0153.JPG SP010.JPG[/TD]
[/TR]
</tbody>[/TABLE]



WHat should be the code to execute the file renaming where it asks for root folder and renames images as per input say starts from B4 till B500 and output as C4 till C500. given there are many blank spaces in between.

I believe both columns need to contain the file extension as well.. right??

Would be really helpful if you can suggest something on it.

Eagerly waiting for a reply...:)

Regards
Mann
 
Upvote 0
Hi Mann, I must admit I have found your questions a bit confusing. Sorry, I don't have any time today, unfortunately, but tomorrow, I'll post a little video here which will show you how to rename files using VBA.
 
Upvote 0
Hi There,As per your directions, I have managed to pull the above data into just 2 columns. 1 being Input and other being output in a new Tab of the same excel.However it contains empty cells in between.Actual Example: [TABLE="width: 443"]
<tbody>[TR]
[TD]Input[/TD]
[TD][/TD]
[TD]Output[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]DSC_0133[/TD]
[TD][/TD]
[TD]ren DSC_0133.JPG SP002.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0138[/TD]
[TD][/TD]
[TD]ren DSC_0138.JPG SP003.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0139[/TD]
[TD][/TD]
[TD]ren DSC_0139.JPG SP004.JPG[/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD]DSC_0150[/TD]
[TD][/TD]
[TD]ren DSC_0150.JPG SP007.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0151[/TD]
[TD][/TD]
[TD]ren DSC_0151.JPG SP008.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0152[/TD]
[TD][/TD]
[TD]ren DSC_0152.JPG SP009.JPG[/TD]
[/TR]
[TR]
[TD]DSC_0153[/TD]
[TD][/TD]
[TD]ren DSC_0153.JPG SP010.JPG[/TD]
[/TR]
</tbody>[/TABLE]
WHat should be the code to execute the file renaming where it asks for root folder and renames images as per input say starts from B4 till B500 and output as C4 till C500. given there are many blank spaces in between.I believe both columns need to contain the file extension as well.. right??Would be really helpful if you can suggest something on it.Eagerly waiting for a reply...:)RegardsMann
I'm not quite sure what you are trying to do but to get rid of the spaces, sort the data. You can do it manually or you can have the code do it before you run your renaming routine. I was lazy and just recorded a quick sort as shown below:

Sub testsort()
'
' testsort Macro
Columns("A:B").Select
Application.CutCopyMode = False
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1:A7"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:B7")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply​
End With
End Sub
Hope this helps
 
Upvote 0
Hi Harry,

Okay, will wait...

Rgds
mann

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
Hi,

Try code below



Code:
Sub GetFileList()    Dim folderPath As String, nextFile As String, i As Long
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show Then
            Range("A:C").ClearContents
            Range("A1") = "Path:"
            folderPath = .SelectedItems(1)
            Range("B1") = folderPath
            nextFile = Dir(folderPath & "\*.*")
            i = 3
            Do While nextFile <> ""
                Cells(i, "A") = nextFile
                i = i + 1
                nextFile = Dir
            Loop
            Columns(1).EntireColumn.AutoFit
        Else
            MsgBox "No folder selected"
        End If
    End With
End Sub


Sub ChangeFileName()
    Dim folderPath As String, nextFile As String, i As Long, lr As Long
    Dim oldName As String, newName As String
    folderPath = Range("B1").Value
    lr = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 3 To lr
        oldName = Cells(i, "A")
        newName = Cells(i, "B")
        If newName <> "" Then
            oldName = folderPath & "\" & oldName
            newName = folderPath & "\" & checkSuffix(oldName, newName)
            If Not fileExists(newName) Then
                Name oldName As newName
                Cells(i, "C") = "Complete"
            Else
                Cells(i, "C") = "Failed"
            End If
        End If
    Next i
    Shell "Explorer " & folderPath, vbNormalFocus
End Sub


Function fileExists(ByVal str As String) As Boolean
    fileExists = (Dir(str) <> "")
End Function


Function checkSuffix(ByVal o As String, n As String)
    Dim f, s
    f = Split(o, ".")
    s = f(UBound(f))
    If Right(n, Len(s)) = s Then
        checkSuffix = n
    Else
        checkSuffix = n & "." & s
    End If
End Function

Does it help?
 
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