Public Function fncRenameFiles(ByVal theSourcePath As String, _
Optional ByVal theFile As String = "*", _
Optional ByVal theExtension As String = "*", _
Optional ByVal prefix As String = "", _
Optional ByVal suffix As String = "", _
Optional ByVal secondRename As Boolean = False)
' Note:
'
' not much validation on this function, so:
'
' don't add extension (.bat, .xlsx, etc) to "theFile"
' don't ad "." to the "theExtension (simply "bat" or "xlsx")
'
' theSourcePath must be valid path
'
' make sure none of the Files to be renamed are opened
' by another program.
'
Dim sFile As String
Dim col As New Collection
Dim i As Integer
Dim sName As String, sExt As String
Dim bolOK As Boolean
' if nothing to do exit sub
If Len(prefix) = 0 And Len(suffix) = 0 Then
Exit Function
End If
If Right$(theSourcePath, 1) <> "\" Then
theSourcePath = theSourcePath & "\"
End If
sFile = Dir$(theSourcePath & theFile & theExtension)
'put all files in collection
Do Until Len(sFile) = 0
col.Add sFile
sFile = Dir$
Loop
'rename files in collection
For i = 1 To col.Count
sName = Replace$(thisFileName(col(i)), theSourcePath, vbNullString)
sExt = thisExtension(col(i))
'Debug.Print col(i), theSourcePath & prefix & sName & suffix & "." & sExt
'
'agp
'25-aug-2021
'do not rename if already exists
'
If secondRename Then
sName = Mid$(sName, Len(prefix) + 1)
If Len(suffix) <> 0 Then
sName = Left$(sName, Len(sName) - Len(suffix))
End If
End If
bolOK = Len(Dir$(theSourcePath & prefix & sName & suffix & "." & sExt)) = 0
If bolOK Then
Name theSourcePath & col(i) As (theSourcePath & prefix & sName & suffix & "." & sExt)
End If
Next
'Msgbox "Done Renaming."
End Function
Private Function thisFileName(ByVal pFile) As String
Dim i As Integer
thisFileName = pFile
i = InStrRev(pFile, ".")
If i > 0 Then
thisFileName = Left(pFile, i - 1)
End If
End Function
Private Function thisExtension(ByVal pFile) As String
Dim i As Integer
thisExtension = pFile
i = InStrRev(pFile, ".")
If i > 0 Then
thisExtension = Mid(pFile, i + 1)
End If
End Function