Hello Riz,
Sorry for the late reply. There we several emergencies I had to deal with after my last post.
Here is the new workbook and code. Test it out and let me know if this what you need.
' Thread: http://www.excelforum.com/excel-programming-vba-macros/1057893-vb-code-get-2-latest-file-names-from-directory.html
' Poster: Riz
Option Explicit
Function GetFileDates(ByVal Folderpath As Variant, ByVal Filename As String, Optional ByVal Descending As Boolean) As Variant
Dim fDate As Variant
Dim fDates As Variant
Dim File As Object
Dim Files As Object
Dim Folder As Variant
Dim LB As Long
Dim j As Long
Dim n As Long
Dim Newest As Date
Dim Sorted As Boolean
Dim tmpDate As Variant
Dim UB As Long
With CreateObject("Shell.Application")
Set Folder = .Namespace(Folderpath)
If Folder Is Nothing Then Exit Function
End With
Set Files = Folder.Items
Files.Filter 64, Filename & "*.*"
ReDim fDates(Files.Count - 1, 1)
' Save the file name and the data in fDates.
For Each File In Files
' 3 = Date Modified, 4 = Date Created, 5 = Date Last Accessed
fDates(n, 0) = File.Name
fDates(n, 1) = CDate(Folder.GetDetailsOf(File, 4))
n = n + 1
Next File
' Sort the files by date using a modified bubble sort.
LB = LBound(fDates, 1)
UB = UBound(fDates, 1)
Do
n = 0
For j = LB To UB - 1
If Descending Xor (fDates(j, 0) > fDates(j + 1, 0)) Then
tmpDate = fDates(j + 1, 0)
fDates(j + 1, 0) = fDates(j, 0)
fDates(j, 0) = tmpDate
tmpDate = fDates(j + 1, 1)
fDates(j + 1, 1) = fDates(j, 1)
fDates(j, 1) = tmpDate
n = j
End If
Next j
UB = n
Loop Until UB = 0
GetFileDates = fDates
End Function
Sub Macro1()
Dim Cell As Range
Dim ChkBox As Object
Dim Filename As String
Dim Folderpath As Variant
Dim fDates As Variant
Dim Rng As Range
Set ChkBox = ActiveSheet.Shapes(Application.Caller)
Set Rng = Range("K1", Cells(Rows.Count, "K").End(xlUp))
If Rng Is Nothing Then Exit Sub
For Each Cell In Rng
If ChkBox.ControlFormat.Value = xlOn Then
Folderpath = Cell & Cell.Offset(0, 1)
Filename = Range("A15")
fDates = GetFileDates(Folderpath, Filename, True)
If Not IsEmpty(fDates) Then
Cell.Offset(0, 2).Resize(1, UBound(fDates) + 1).Value = Application.Transpose(Application.Index(fDates, 0, 1))
End If
Else
If Not IsEmpty(Cell.Offset(0, 2)) Then
Range(Cell.Offset(0, 2), Cells(Cell.Row, Columns.Count).End(xlToLeft)).ClearContents
End If
End If
Next Cell
End Sub
Bookmarks