Vba

ericlch16

Active Member
Joined
Nov 2, 2007
Messages
313
Office Version
  1. 2016
  2. 2013
Platform
  1. Windows
I have a folder which contains archive files. I want a VBA to keep the 5 most recent files. Any help?
I did a loop to kill the file but what is the most efficient way to keep the 5 most recent ones and delete the rest?
 

Excel Facts

Easy bullets in Excel
If you have a numeric keypad, press Alt+7 on numeric keypad to type a bullet in Excel.
Are the "dates" to evaluate in the file names? If so, please provide several accurate examples of the filenames, as well as the path to these files.
 
Upvote 0
no.. the date is the window filename last update. i have a function which gets the timestamp of the file. I have a VBA code below which i used to delete files that are more that 7 days old. but now i want to keep the 5 most recent files and delete the rest. any idea?? do i have to loop and get all the time stamps.. what is the most efficient way to do it??

__________________________

Archivedirectory = path2 & "Archive\"
myvar = Empty
myvar = FileList(Archivedirectory)
If TypeName(myvar) <> "Boolean" Then
For i = LBound(myvar) To UBound(myvar)
timeofFILE = FileDateTime(Archivedirectory & myvar(i))
If (timeofFILE < Now() - 7) Then
Kill (Archivedirectory & myvar(i))' this kills those for over 7 days
Else

End If
Next
Else
'MsgBox "No files found"
End If
 
Upvote 0
I think it's important to know the naming convention you are using - since you can't simply have seven files of the same name in a folder even if they have different time stamps. We need to have some way of knowing what files belong together (so as to evaluate which of them are the most recent and which of them can be deleted).
 
Upvote 0

Forum statistics

Threads
1,224,548
Messages
6,179,443
Members
452,915
Latest member
hannnahheileen

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top