VBA Delete Files over 90 Days Old

VBA Delete Files over 90 Days old

VBA Delete Files over 90 Days old from a folder in Excel. In this following tutorial, we are going to see how to delete older files which can be any number of days. Here we are checking for 90 days. You can change this number. It can be one week, one month, quarter, or year.

VBA Delete Files over 90 Days old

Let us see an example VBA macro code to delete files over 90 days old from a folder in Excel. In the following example we are specifying folder path. Once we specify the folder path checking whether it is exists or not. If it is existed the looping through each file in a folder. If file is older than 90 days then we are deleting that file. Here we are checking older than 90 days files. You can change this number according to your requirement. Just define required number to ‘iDays’. I have specified my folder as ‘C:\VBAF1\Test\’. Before running macro you can change this folder path.


'VBA Delete All Files over 90 Days old
Sub VBAF1_Delete_Files_over_90_Days_old()
    
    'Variable declaration
    Dim sFolderPath As String
    Dim iDays As Integer
    
    'Define Folder Path
    sFolderPath = "C:\VBAF1\Test\"
    
    'Specify 90 Days . You can change this value according to your requirement.
    iDays = 90 '
    
    'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    
    'Check Specified Folder exists or not
    If oFSO.FolderExists(sFolderPath) Then
        'Loop through each file in a specified folder
        For Each oFile In oFSO.GetFolder(sFolderPath).Files
            'Check each file if it is older than 90 days or not
            If DateDiff("d", oFile.DateLastModified, Now) > iDays Then
                'If file is older than 90 days delete
                oFile.Delete
            End If
        Next
     End If
     
End Sub

Note: Check specified folder before and after running macro to see the changes.

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel VBA Tables and ListObjects

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

2 thoughts on “VBA Delete Files over 90 Days Old”

Leave a Comment