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
            End If
     End If
End Sub

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

Instructions to use VBA Macro Code

Here are the instructions to use above macro in Visual basic editor.

  • Open Visual Basic Editor(VBE) by clicking Alt +F11
  • Go to code window by clicking F7
  • Copy above specified macro or procedure
  • Paste above copied code in code window
  • Run macro by clicking F5 or Run command
  • Check specified folder to check all the older files which are 90 days old are deleted or not.

Related Articles

You can also learn complete details like syntax, example and etc by clicking on the following buttons.

VBA File and Directory Functions in Excel Related Posts

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

Leave a Comment

Your email address will not be published. Required fields are marked *