2016-02-28 80 views
1

我試圖刪除與名稱相同,但不同的創建日期的舊文件練級最新的文件刪除與名稱相同,但不同的創建日期的舊文件留下最新的文件

我有這樣一個文件夾中的文件:

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 
+0

我會說,你正在試圖讀取超出了集合的末尾。我對vba知之甚少,無法確定哪裏出錯 - 即哪個「i」或「j」超出了界限。 – ChrisF

+0

只是基於@ ChrisF的評論的猜測,但也許'殺死集合(2)'。 –

回答

1

需要一個對象,因爲有沒有在你coll初始化的對象。 看這條線:

collection.Add fcount 

fcount沒有初始化,您可能想要做

collection.Add fsoFile 
+0

我從fes不同的來源提出togeather,這是一個oversite,謝謝 – xyz

相關問題