Rechercher dans ce blog

Chargement...

jeudi 3 septembre 2009

Trier une ListBox Access

Lorsqu'on a une ListBox dont la SourceType est une ValueList, comment la trier ?
Réponse ci-dessous, avec possibilité de trier sur n'importe quelle colonne, en mode numérique ou alpha.
Sub SortListBox(ByRef lstBox As ListBox, iCol As Integer, Optional isNum As Boolean = False)

'sorts the value list of a listbox on any column
'numerical col. can be sorted numerically or alpha
'sorting algorithm is probably not the most efficient
'Copyleft: Patrick Honorez - www.idevlop.com
Dim vaItems As Variant, cols As Integer
Dim i As Long, j As Long, k As Integer
Dim vTemp As String, IsSwapped As Boolean
Dim isSmaller As Boolean
On Error GoTo 0
'Put the items in a variant array
vaItems = Split(lstBox.RowSource, ";")
cols = lstBox.ColumnCount
Do
IsSwapped = False
For i = 0 To lstBox.ListCount - 2
j = i + 1
If isNum Then
isSmaller = Val(vaItems(i * cols + iCol - 1)) > _
Val(vaItems(j * cols + iCol - 1))
Else
isSmaller = vaItems(i * cols + iCol - 1) > _
vaItems(j * cols + iCol - 1)
End If
If isSmaller Then
For k = 0 To cols - 1
'swap row i and row j
IsSwapped = True
vTemp = vaItems(i * cols + k)
vaItems(i * cols + k) = (vaItems(j * cols + k))
vaItems(j * cols + k) = vTemp
Next k
End If
Next i
Loop While IsSwapped
'Add the sorted array back to the listbox
lstBox.RowSource = Join(vaItems, ";")
Me.Repaint
End Sub