使用目录中最近 10 个最新文件夹的列表填充组合框

Populate a combo box with a list of last 10 latest folders from a directory

我有一个组合框,我想在其中填充指定目录中最近 10 个文件夹的列表。说,

有 40 个文件夹。在组合框中,它应该列出最新的 10 个文件夹。

谢谢,

Private Sub UserForm_Initialize()
Dim name

  For Each name In ListDirectory(Path:="C:\Users\AllertonFC\Documents\FA Level 1 & Level 2\", AttrInclude:=vbDirectory, AttrExclude:=vbSystem Or vbHidden)
    Me.ComboBox1.AddItem name
  Next name
End Sub

Function ListDirectory(Path As String, AttrInclude As VbFileAttribute, Optional AttrExclude As VbFileAttribute = False) As Collection
  Dim Filename As String
  Dim Attribs As VbFileAttribute

  Set ListDirectory = New Collection

  ' first call to Dir() initializes the list
  Filename = Dir(Path, AttrInclude)

  While Filename <> ""
    Attribs = GetAttr(Path & Filename)
    ' to be added, a file must have the right set of attributes
    If Attribs And AttrInclude And Not (Attribs And AttrExclude) Then
      ListDirectory.Add Filename, Path & Filename
    End If
    ' fetch next filename
    Filename = Dir
  Wend
End Function

这应该可行,我发现将值放入字符串并在最后一刻将其拆分为数组更容易,也不使用 Dir,而是使用 Scripting.FileSystemObject

Public Sub cBoxFiller()
   Dim oFS As Object, SrcFldr As String, oFldr As Object, xFldr As Object
   Dim FldrsTxt As String, FldrsAR() As String, GudCtr As Long
   Dim cBoxTxt As String, i As Long

   SrcFldr = "C:\Users\AllertonFC\Documents\FA Level 1 & Level 2\"
   Set oFS = CreateObject("Scripting.FileSystemObject")
   Set oFldr = oFS.getfolder(SrcFldr)

   ' Generate an Array of ALL SubFolders
     FldrsTxt = ""
     For Each xFldr In oFldr.subFolders
        FldrsTxt = IIf(FldrsTxt = "", "", FldrsTxt & vbCrLf) & xFldr.name  ' or xFldr.Path
     Next xFldr
     FldrsAR = Split(FldrsTxt, vbCrLf)
   ' Done

   ' Build a String of Last 10 Folders - separated by VbCrLf
     GudCtr = 0
     For i = UBound(FldrsAR) To LBound(FldrsAR) Step -1
        If GudCtr < 10 Then
           GudCtr = GudCtr + 1
           cBoxTxt = IIf(cBoxTxt = "", "", cBoxTxt & vbCrLf) & FldrsAR(i)
        End If
     Next i
   ' Done

   ' Split into an Array & Assign to the ComboBox
     ComboBox1.List = Split(cBoxTxt, vbCrLf)
   ' Done
End Sub