2012-09-06 35 views
0

此代码填充一个ListBox与特定的文件夹如何对文件进行排序然后填充ListBox?

Dim DIRECTORY As String 
DIRECTORY = Dir(myPath & "\*.xlsx", vbNormal) 
Do Until DIRECTORY = "" 
ListBox1.AddItem DIRECTORY 
DIRECTORY = Dir() 
Loop 

的文件名,但我希望有一个排序列表。
我怎样才能先排序文件,然后填充列表框。
btw排序列表框是(据我所知)一个很长的过程。

回答

1

A ListBox没有内置排序功能。你将需要推出自己的。

其基本思路是将列表数据放入数组中,对数组进行排序,然后将数据放回列表中。排序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 
相关问题