xyz
xyz

Reputation: 2300

Delete old files with same name but different created dates leaving newest file

I am trying to Delete old files with same name but different created dates leveling newest file

I have files in a folder like:

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

I want:

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

I get the error

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

Code

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

Upvotes: 1

Views: 128

Answers (1)

Zwo
Zwo

Reputation: 1113

An object is required because there are not initialized objects in you coll. Look this line :

collection.Add fcount

fcount is not initialized, you may want to do

collection.Add fsoFile

Upvotes: 2

Related Questions