我正在尝试删除具有相同名称但不同的创建日期调整最新文件的旧文件
我的文件夹在以下文件夹中:
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 :(得分:2)
由于您coll
中没有初始化对象,因此需要一个对象。
看这一行:
collection.Add fcount
fcount
未初始化,您可能想要
collection.Add fsoFile