これは古い質問ですが、この正確な解決策が必要だったので、ここに追加すると思いました。このコードは、ファイル名が文字列比較によってソート可能なもので終わることを想定しているため、SomeName_YYYY-MM-DD 形式のファイルである可能性があります。24 時間制のタイムスタンプも組み込むことができます。このプロセスではファイルの名前が変更されないため、増分数値スキームは他のコードで慎重に管理する必要があります (つまり、ファイル名に _1、_2 などを追加する必要があります)。
このソリューションは、配列よりもはるかに優れたこの目的を果たすコレクションを活用することに注意してください。
Public Sub CleanBackups(filePathAndBaseName As String, fileExtension As String, maxCopiesToKeep As Integer)
'
' Calling Example
' CleanBackups "C:\Temp\MyLog", ".txt", 5
'
' The above example would keep only the 5 versions of the file pattern "C:\Temp\MyLog*.txt"
' that are "LARGEST" in terms of a string comparison.
' So if MyLog_1.txt thru MyLog_9.txt exist, it will delete MyLog_1.txt - MyLog_4.txt
' and leave MyLog_5.txt - MyLog_9.txt
' Highly recommend using pattern MyLog_{YYYY-MM-DD_HhNn}.txt
Dim pathOnly As String
Dim foundFileName As String
Dim oldestFileIndex As Integer
Dim iLoop As Integer
Dim fileNameCollection As New Collection
pathOnly = Left(filePathAndBaseName, InStrRev(filePathAndBaseName, "\"))
foundFileName = Dir(filePathAndBaseName & "*" & fileExtension, vbNormal)
Do While foundFileName <> ""
fileNameCollection.Add foundFileName
foundFileName = Dir
Loop
Do While fileNameCollection.Count > maxCopiesToKeep
' Find oldest file, using only the name which assumes it ends with YYYY-MM-DD and optionally a 24-hour time stamp
oldestFileIndex = 1
For iLoop = 2 To fileNameCollection.Count
If StrComp(fileNameCollection.Item(iLoop), fileNameCollection.Item(oldestFileIndex), vbTextCompare) < 0 Then
oldestFileIndex = iLoop
End If
Next iLoop
Kill pathOnly & "\" & fileNameCollection.Item(oldestFileIndex)
fileNameCollection.Remove oldestFileIndex
Loop
End Sub