VB 从f盘读取最近5个xls文件名到text1中,且按时间降序排
f盘有多个Excel文件,将最新建立的5个Excel文件名放到text1中,文件名(汉字无后缀)按时间降序排。求代码,谢谢[此贴子已经被作者于2019-8-13 13:26编辑过]
Option Explicit Private Sub Command1_Click() Dim ObjFileSystem As New FileSystemObject '需引用Microsoft Scripting Runtime Dim ObjFolder As Folder '文件夹 Dim ObjFile() As File '文件 Dim FDateCreated() As Date '每个文件创建时间 Dim FileTotal As Integer 'excel文件总数 Dim i As Integer Set ObjFolder = ObjFileSystem.GetFolder("F:\") ''查找文件(F:\) Dim tempFile As File FileTotal = 0 For Each tempFile In ObjFolder.Files ''遍历文件夹中所有文件 If Right(tempFile.Name, 4) = ".xls" Then ''后缀为.xls为Excel文件 FileTotal = FileTotal + 1 ReDim Preserve ObjFile(1 To FileTotal) ''数组长度加1,且保留原内容 Set ObjFile(FileTotal) = tempFile End If Next ReDim FDateCreated(1 To FileTotal) For i = 1 To FileTotal FDateCreated(i) = ObjFile(i).DateCreated ''获取每个文件创建时间 Next ''将ObjFile数组中的数据排序 Dim j As Integer Dim tempD As Date Dim tempF As File For i = 1 To FileTotal For j = 1 To FileTotal - 1 If FDateCreated(j) < FDateCreated(j + 1) Then ''比较创建时间大小,时间大的就是最新创建的 tempD = FDateCreated(j) FDateCreated(j) = FDateCreated(j + 1) FDateCreated(j + 1) = tempD Set tempF = ObjFile(j) Set ObjFile(j) = ObjFile(j + 1) Set ObjFile(j + 1) = tempF End If Next Next ''将数组中top5数据显示出来 Text1.Text = "" For i = 1 To 5 Text1.Text = Text1.Text & Left(ObjFile(i).Name, Len(ObjFile(i).Name) - 4) & vbCrLf Next End Sub