Link to home
Create AccountLog in
Avatar of nicoleheritage

asked on

Sort files under a folder in descending order


I need an excel vba code which could sort files under a folder (C:\My Documents\Ushank) in descending order.
The path where the files are stored is entered in the excel workbook. I want to read that path and sort all the files under the specified path in descending order.

Can someone please provide me a code which can do this?
Avatar of Patrick Matthews
Patrick Matthews
Flag of United States of America image


Descending order based on what parameter?  File name?  created date?  modified date?  Something else?


1) Sort is descending by file name

2) The specified folder is in B1

3) A3 has a heading called "Files"

4) Results go to A4:A???

then this code should work:

Sub GetAndSortFiles()
    Dim fso As Object
    Dim fld As Object
    Dim fil As Object
    Dim DestRow As Long
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set fld = fso.GetFolder([b1])
    DestRow = 3
    For Each fil In fld.Files
        DestRow = DestRow + 1
        Cells(DestRow, 1) = fil.Name
    [a3].Sort Key1:=[a3], Order1:=xlDescending, Header:=xlYes
    Set fil = Nothing
    Set fld = Nothing
    Set fso = Nothing
End Sub

Open in new window

Avatar of Arno Koster
Arno Koster
Flag of Netherlands image

Link to home
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer