Sub ReName (see below) works for me
- my sample data has not been cleared from attached workbook
- your file names may have some oddities that you have not mentioned!
- amended VBA TestReName also included in the attached file
- run with {CTRL} K
- amend the folder path first (must end with "\")
- old values are cleared by the VBA each time
- TestReName dumps values to the 2 worksheets but does not rename any files
The VBA looks at all files in the folder (with *.*)
- to only consider jpegs, amend this line:
fileStr = Dir(InvFolder & "*.*")
- to:
fileStr = Dir(InvFolder & "*.jpg")
If TestReName does what you need you can either:
- run ReName
OR
- amend TestReName
-by removing the comment apostrophe at beginning of the line
'Name InvFolder & fileStr As InvFolder & newFileStr 'REMOVE COMMENT FLAG TO ACTIVATE
Name InvFolder & fileStr As InvFolder & newFileStr
If TestReName does not do exactly what you need, then re-attach the workbook with your data and highlight problem names
(there may be extra spaces etc in your file names)
Const InvFolder = "C:\TestArea\Invoices\" 'AMEND
Sub ReName()
Dim fileStr As String, newFileStr As String, oldNum As String, newNum As String, InvFolder As String
Dim x As Variant, a As Integer, c As Integer
Sheets(1).UsedRange.ClearContents
InvFolder = "C:\TestArea\Invoices\" 'AMEND
fileStr = Dir(InvFolder & "*.*")
Do Until fileStr = ""
oldNum = ""
For c = 1 To Len(fileStr)
x = Mid(fileStr, c, 1)
If x <> "" And IsNumeric(x) Then
oldNum = oldNum & x
End If
Next c
newNum = Format(oldNum, "00000")
newFileStr = Replace(fileStr, oldNum, newNum)
'write record to sheet
a = a + 1
With Sheets(1)
.Cells(a, 1) = fileStr
.Cells(a, 2) = newFileStr
End With
'rename files
Name InvFolder & fileStr As InvFolder & newFileStr
fileStr = Dir
Loop
End Sub
Bookmarks