• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

I want that in my backup folder only 10 latest file be there and rest will be automatically deleted

Ankur Kumar

New Member
Hi,

I using VBA code for auto backup of my workup when i close it it will take auto backup of it now i want only latest 10 files will be there and older files will automatically deleted, here is my code please advice how can i do that.


Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)

On Error Resume Next


Application.DisplayAlerts = False


Dim backupfolder As String

backupfolder = "D:\Auto Backup Sales Tracker\Closed\"

ThisWorkbook.SaveCopyAs Filename:=backupfolder & " " & Format(Now, "dd-mmm-yy h-mm-ss") & " " & ActiveWorkbook.Name

ThisWorkbook.Save

Application.DisplayAlerts = True

  

End Sub
 
Last edited by a moderator:
https://stackoverflow.com/questions/27550992/excel-vba-leave-5-newest-backups-and-delete-the-rest


Code:
Sub DeleteOldFiles()
    Dim fso As New FileSystemObject
    Dim fil As File
    Dim oldfile As File
    Dim BackUpPath As String 'This is the FOLDER where your backups are stored

    Do Until fso.GetFolder(BackUpPath).Files.Count < 11
        For Each fil In fso.GetFolder(BackUpPath).Files
            'Checks to see if this file is older than the oldest file thus far
            If oldfile Is Nothing Then Set oldfile = fil
            If oldfile.DateLastModified > fil.DateLastModified Then Set oldfile = fil
        Next fil
        fso.DeleteFile oldfile, True
        Set oldfile = Nothing
    Loop

End Sub
 
Back
Top