I need a code to look in my C drive for specific folders.
I want it to go through the first folder and keep drilling in all the subfolders until it hits a dead end, and then go back to second folder and do the same etc..., looking for any folder or file older than 2 years and delete it.

This is the code I have:

Private Sub FileCleanUp(strPath As String)

    Dim m_objFSO As Scripting.FileSystemObject
    Dim objFolder As Scripting.Folder
    Dim objFile As Scripting.File
    Dim dDeleteDate As Date
    Dim sDirectorypath
    
    sDirectorypath = "C:\myfolder" 'what should I replace this with to look in ALL                 'folders and subfolders?
    
    dDeleteDate = DateAdd("m", -3, Now())
    
    Set m_objFSO = New Scripting.FileSystemObject

    Set objFolder = m_objFSO.GetFolder(strPath)
    
    For Each objFile In objFolder.Files
        If Format(objFile.DateLastModified, "YYYY-MM-DD") <= Format(dDeleteDate, "YYYY-MM-DD") Then
            m_objFSO.DeleteFile (strPath & objFile.Name)
        End If
    Next objFile
    
    Set m_objFSO = Nothing


End Sub

Have you designed the program yet, or are you just tossing code around to see it it works?

This is the type or program you need to plan before starting to code. Design a roadmap of what needs to happen
1) when you find a directory
2) when you start looking at the directory contents
3) when you reach the end of the directory
What is the interaction between all of these actions?

A good design will almost write the code itself. Then all you need to worry about is the syntax of the language.

I am a lawyer and never programmed before...
I need to make this code running and i do not know how , that is why i am using this website to get some help!

Thanks

I am a lawyer and never programmed before...

Then you obviously know the importance of pre-planning before jumping into the fire.

IMO, if you've never programmed before, it might be worthwhile to pay someone since this is not a trivial program. And you could actually help a college student with his resume at the same time. N'est-ce pas?

FormatDateTime(objFile.DateLastModified,2) will return MM/DD/YYYY

This is one of the most obvious applications for the use of recursion but it is not really for the faint hearted. As WaltP says this needs some design however in simple terms you write a subroutine that takes a folder as an argument.

the code in this subroutine processes all the objects within the folder. when it encounters a sub-folder it calls itself to process that subfolder.

When the subroutine finishes processing every object in the folder it simply returns.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.