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