Delete all but newest file
John,
NOTE: be very cautious when doing something like this. The file deleted
will not end up in the recycle bin.
I used the Excel standard for the first day of Jan 1, 1980. If your files
are earlier than that you may need to redefine dummydate. I used the
Workbook_Open event to allow the user to select a folder location, but you
may move all the code to one standard module procedure if you like.
In the ThisWorkbook Module put:
Private Sub Workbook_Open()
Dim foldername As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
foldername = .SelectedItems(1)
End With
ShowFolderList (foldername)
End Sub
AND in a standard module put:
Sub ShowFolderList(folderspec)
Dim fs, f1
Dim dummydate As Date
dummydate = "1/1/1980"
Set fs =
CreateObject("Scripting.FileSystemObject").GetFold er(folderspec).Files
For Each f1 In fs
If DateDiff("s", f1.datelastmodified, dummydate) < 0 Then
dummydate = f1.datelastmodified
Else: f1.Delete
End If
Next
For Each f1 In fs
If DateDiff("s", f1.datelastmodified, dummydate) 0 Then f1.Delete
Next
End Sub
Mike
"JohnUK" wrote:
Hi All,
I am after a piece of code that deletes all files within a folder with the
exception of the latest file created.
Again any help greatly appreciated
John
|