'VBA: Problem with getting last two recent files of specific folder

I am trying to recieve the last two recent files of a specific folder and mostly my code is working fine:

Dim FileSys, objFile, myFolder, c As Object

  FolderName = ("C:\Users\asd\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".csv") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename2 = strFilename
                    strFilename = objFile.Name
                End If
            End If
        Next objFile

The problem I am having is, if the most recent file is from 2022 and the second most recent file is from 2021, the first objFile is the file from 2022 and he is not checking any older ones.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source