删除具有相同名称但不同创builddate的旧文件,留下最新的文件

我想删除具有相同名称的旧文件,但不同的创builddate水平最新的文件

我有一个文件夹中的文件,如:

CONNECT 2016 - elements - 2016.02.28.csv CONNECT 2016 - elements - 2016.02.27.csv Export Step Three_16-02-28 10.51.csv Export Step Three_16-02-28 10.00.csv Export Step Three_16-02-27 1.10.csv 

我想要:

 CONNECT 2016 - elements - 2016.02.28.csv Export Step Three_16-02-28 10.51.csv 

我得到错误

 Object required This is highlighted If coll(i).DateCreated < coll(j).DateCreated Then 

 Sub DeleteOlderFiles() Dim fso, fcount, a Dim fsoFolder As Folder Dim fsoFile As File Dim collection As New collection Dim obj As Variant Dim filename As String Dim i As Long, j As Long Set fso = CreateObject("Scripting.FileSystemObject") Set fsoFolder = fso.GetFolder(ThisWorkbook.path & "\Files to Combine\") 'add each file to a collection a = Array("Export Step Three", "bushCONNONECT") For j = LBound(a) To UBound(a) For Each fsoFile In fsoFolder.files If fsoFile.Name Like a(j) & "*" Then 'For Each fcount In fsoFolder.files collection.Add fcount End If Next fsoFile 'sort the collection descending using the CreatedDate Set collection = SortCollectionDesc(collection) For i = 2 To collection.Count Kill collection(i) Next i Next j End Sub Function SortCollectionDesc(collection As collection) 'Sort collection descending by datecreated using standard bubble sort Dim coll As New collection Set coll = collection Dim i As Long, j As Long Dim vTemp As Object 'Two loops to bubble sort For i = 1 To coll.Count - 1 For j = i + 1 To coll.Count If coll(i).DateCreated < coll(j).DateCreated Then 'store the lesser item Set vTemp = coll(j) 'remove the lesser item coll.Remove j 're-add the lesser item before the greater Item coll.Add Item:=vTemp, before:=i Set vTemp = Nothing End If Next j Next i Set SortCollectionDesc = coll End Function 

一个对象是必需的,因为你的coll中没有初始化对象。 看这一行:

 collection.Add fcount 

fcount没有初始化,你可能要这样做

 collection.Add fsoFile