Reputation: 293
In a folder I have some images named 1;2;3;4;5;6 for example and I need to change the name of each one like this :
1 become 6 / 2 become 5 / 3 become 4 ... etc
This example work with 6 images but i can have many more.
I start some work for looping throught all files in a directory
Sub LoopThroughFiles()
Dim StrFile As String
StrFile = Dir("c:\xxx\*test*")
Do While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
Loop
End Sub
I may need to copy them in an another folder because I can't name a file 6 if there is already one ?
Thank's for the help
Upvotes: 0
Views: 537
Reputation: 13386
you could use this:
Public Sub SwapFiles()
Dim folderPath As String
Dim fileCount As Long
folderPath = "c:\xxx" ' folder path to search files into
With CreateObject("Scripting.FileSystemObject")
For fileCount = 1 To 3
.CopyFile folderPath & "\" & fileCount & ".jpg", folderPath & "\" & "temp.jpg"
.CopyFile folderPath & "\" & (6 - fileCount + 1) & ".jpg", folderPath & "\" & fileCount & ".jpg"
.CopyFile folderPath & "\" & "temp.jpg", folderPath & "\" & (6 - fileCount + 1) & ".jpg"
Next
End With
End Sub
just change "jpg" to your actual image files extension
Upvotes: 1
Reputation: 1070
You cannot rename file "1" to "6" if the "6" is still there, so we need to first rename each file to a temporary name. For this reason we loop all files in the folder twice. Note that the files must be named numbers only (plus extension), or the code will fail. Back-up your images before running the script.
Public Sub rename_all_files_in_folder(folderPath As String)
''' for this code to work, Microsoft Scripting Runtime reference is required (Tools -> References)
Const temp_filename_prefix As String = "to_be_renamed_"
Dim fso As Scripting.FileSystemObject
Dim f As Scripting.file
Dim fileCount As Integer
Dim newFilename As String
Dim extension As String
Set fso = New FileSystemObject
fileCount = 0
If fso.FolderExists(folderPath) Then
''' first cycle, each file gets temporary name
For Each f In fso.GetFolder(folderPath).Files
fileCount = fileCount + 1
'fso.FindFileInFolder = f.Name
f.Name = temp_filename_prefix & f.Name
Next f
''' second cycle to rename from temporary name to new name
For Each f In fso.GetFolder(folderPath).Files
extension = "." & fso.GetExtensionName(f.path)
newFilename = CStr(fileCount + 1 - CInt(Replace(Replace(f.Name, temp_filename_prefix, ""), extension, ""))) & extension
f.Name = newFilename
Next f
Else
MsgBox "Folder not found:" & vbCrLf & folderPath
End If
End Sub
Upvotes: 1