-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRenumberFiles-Module.txt
More file actions
67 lines (59 loc) · 2.77 KB
/
RenumberFiles-Module.txt
File metadata and controls
67 lines (59 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Option Explicit
Sub RenumberFiles()
Dim folderPath$, fileName$, newName$
Dim fso As Object, folder As Object, file As Object
Dim regEx As Object, matches As Object
Dim startNum&, endNum&, padLength&, increment&
Dim fromIndex&, toIndex&, stepVal&, fileCount&, i&
Dim inputStr$, inputValues As Variant, files As Collection
Const del$ = "_"
' Select a folder
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a folder"
If .InitialFileName = "" Then .InitialFileName = ThisWorkbook.Path & "\"
If .Show <> -1 Then Exit Sub
folderPath = .SelectedItems(1) & "\"
End With
' Initialize and check folder
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder(folderPath)
fileCount = folder.files.Count
If fileCount <= 0 Then MsgBox "The folder is empty.", vbInformation, "Empty Folder": Exit Sub
' Get and validate user input
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "^\d+,\d+,\d+,-?\d+$"
Do
inputStr = InputBox("Enter: Start, End, Pad, Increment", "Batch Input", "1," & fileCount & ",3,1")
If StrPtr(inputStr) = 0 Then Exit Sub Else inputValues = Split(inputStr & ",,,", ",")
startNum = Val(inputValues(0))
endNum = Val(inputValues(1))
padLength = Val(inputValues(2))
increment = Val(inputValues(3))
If regEx.test(inputStr) And startNum > 0 And startNum <= endNum And endNum <= fileCount And padLength > 0 And padLength < 11 Then Exit Do
MsgBox "Ensure: Start >= 1, End <= " & fileCount & ", Pad: 1-10, Increment != text.", vbExclamation, "Invalid Input"
Loop
' Determine loop direction
If increment > 0 Then
fromIndex = endNum: toIndex = startNum: stepVal = -1
Else
fromIndex = startNum: toIndex = endNum: stepVal = 1
End If
' Collect files
Set files = New Collection
For Each file In folder.files: files.Add file: Next
' Rename matching files
regEx.Pattern = del & "([0-9]+)$"
For i = fromIndex To toIndex Step stepVal
fileName = fso.GetBaseName(files(i))
Set matches = regEx.Execute(fileName)
If matches.Count > 0 Then
newName = regEx.Replace(fileName, del & Format(CLng(matches(0).SubMatches(0)) + increment, String(padLength, "0"))) & "." & fso.GetExtensionName(files(i))
If Dir(folderPath & newName) = "" Then
files(i).Name = newName
ElseIf increment <> 0 Then
MsgBox newName & " already exists.", vbCritical, "Name Conflict": Exit Sub
End If
End If
Next i
MsgBox "Files renamed successfully!", vbInformation, "Success"
End Sub