Sub CreateNewFileName()
Dim newFileName As String, strPath As String
Dim strFileName As String, strExt As String
strPath = "C:\AAA\"
strFileName = "Data"
strExt = ".xls"
newFileName = strFileName & "-" & GetNewSuffix(strPath, strFileName, strExt) & strExt
MsgBox "The new FileName is: " & newFileName
ActiveWorkbook.SaveCopyAs strPath & newFileName
End Sub
Function GetNewSuffix(ByVal strPath As String, ByVal strName As String, ByVal strExt As String) As Integer
Dim strFile As String, strSuffix As String, intMax As Integer
On Error GoTo ErrorHandler
strFile = Dir(strPath & "\" & strName & "*")
Do While strFile <> ""
strSuffix = Mid(strFile, Len(strName) + 2, Len(strFile) - Len(strName) - Len(strExt) - 1)
If Mid(strFile, Len(strName) + 1, 1) = "-" And CSng(strSuffix) >= 0 And _
InStr(1, strSuffix, ",") = 0 And InStr(1, strSuffix, ".") = 0 Then
If CInt(strSuffix) >= intMax Then intMax = CInt(strSuffix)
End If
NextFile:
strFile = Dir
Loop
GetNewSuffix = intMax + 1
Exit Function
ErrorHandler:
If Err Then
Err.Clear
Resume NextFile
End If
End Function
|