此代码使用特定文件夹的文件名填充 ListBox
Dim DIRECTORY As String
DIRECTORY = Dir(myPath & "\*.xlsx", vbNormal)
Do Until DIRECTORY = ""
ListBox1.AddItem DIRECTORY
DIRECTORY = Dir()
Loop
但我想要一个排序列表。
如何先对文件进行排序,然后再填充 ListBox。
顺便说一句,对列表框进行排序(据我所知)是一个很长的过程。
AListBox
没有内置的排序功能。你需要自己动手。
基本思想是将列表数据放入数组中,对数组进行排序,然后将数据放回列表中。有许多很好的参考资料可用于对 VBA 数组进行排序。
除非您有大量文件,否则简单的排序可能就足够了。尝试这个
Sub SortListBox(oLb As MSForms.ListBox)
Dim vItems As Variant
Dim i As Long, j As Long
Dim vTemp As Variant
'Put the items in a variant array
vItems = oLb.List
' Sort
For i = 0 To UBound(vItems, 1) - 1
For j = i + 1 To UBound(vItems, 1)
If vItems(i, 0) > vItems(j, 0) Then
vTemp = vItems(i, 0)
vItems(i, 0) = vItems(j, 0)
vItems(j, 0) = vTemp
End If
Next
Next
'Clear the listbox
oLb.Clear
'Add the sorted array back to the listbox
For i = 0 To UBound(vItems, 1)
oLb.AddItem vItems(i, 0)
Next
End Sub
DIR 命令总是按字母顺序显示元素,但按名称而不是类型排序。正确的做法是利用“vbDirectory”和“vbArchive”属性,首先使用vbDirectory 创建一个列表,然后使用vbArchive 创建另一个列表。结果是一个按字母顺序排序的列表,将目录与文件分开。
Private Sub ListarFunc()
Dim a As Integer
Dim strArchivo As String
Dim FileName As String
Dim TipoArchivo As String
Dim fso As Object, file As Object, folder As Object
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
'If we are not in /root add a "\" to the PathExplorer
If Mid(Me.BoxPathExplorer, 4, 1) <> "" Then Me.BoxPathExplorer = CurDir() & "\"
Me.Lista1.ForeColor = RGB(25, 25, 100)
Me.Lista1.RowSource = "" 'First, clear the list
Me.Lista1.AddItem "___________________ TIPO ___________________" & ";" & "________________ " & _
Dir(Me.BoxPathExplorer, vbVolume) & " ________________"
strArchivo = Dir(Me.BoxPathExplorer, vbDirectory)
While strArchivo <> ""
Set folder = fso.GetFolder(strArchivo)
If folder.Attributes And vbDirectory Then Me.Lista1.AddItem folder.Type & ";" & strArchivo
strArchivo = Dir
Set folder = Nothing
Wend
strArchivo = Dir(Me.BoxPathExplorer, vbArchive)
While strArchivo <> ""
Set file = fso.GetFile(strArchivo)
If file.Attributes And vbArchive Then Me.Lista1.AddItem file.Type & ";" & strArchivo
strArchivo = Dir
Set file = Nothing
Wend
If Lista1.ItemData(1) = "." Then Me.Lista1.RemoveItem 1 'Delete the item '.'
Me.Lista1 = "NoSelection"
End Sub
问候。