VBA Delete Subfolders Older than 30 Days from a folder in Excel. In this following tutorial we are going to see how to delete files and sub-folders which are older than 30 days. Here we are checking for 30 days. You can change this number. It can be one week, one month, quarter, or year.
Let us see an example VBA macro code to delete Subfolders older than 30 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 folder in a specified folder or drive. If file is older than 30 days then we are deleting that folder and all files in it. Here we are checking older than 30 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 Deleting All Files and Subfolders Sub VBAF1_Delete_All_Files_and_Subfolders() 'Variable declaration Dim sFolderPath As String Dim oFSO As FileSystemObject Dim iDays As Integer 'Define Folder Path sFolderPath = "C:\VBAF1\Test\" 'Specify 30 Days . You can change this value according to your requirement. iDays = 30 ' 'Check if slash is added If Right(sFolderPath, 1) = "\" Then 'If added remove it from the specified path sFolderPath = Left(sFolderPath, Len(sFolderPath) - 1) End If 'Create FSO Object Set oFSO = CreateObject("Scripting.FileSystemObject") 'Check Specified Folder exists or not If oFSO.FolderExists(sFolderPath) Then 'Loop through each folder in a specified folder For Each oFld In oFSO.GetFolder(sFolderPath).SubFolders 'Check each folder if it is older than 30 days or not If DateDiff("d", oFld.DateLastModified, Now) > iDays Then 'Delete All Files oFSO.DeleteFile oFld & "\*.*", True 'Delete Subfolder oFSO.DeleteFolder oFld End If Next End If End Sub
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 subfolders and files in it which are 30 days old are deleted or not.
You can also learn complete details like syntax, example and etc by clicking on the following buttons.