AW: Werte in einer Listbox sortieren
05.03.2014 15:36:11
Bastian
Hallo Sebastian,
so geht es auch nur mit VBA. Genutzt wird je ein BubbleSort Algorithmus. Einmal für aufsteigende Sortierung, und einmal für absteigende Sortierung.
Gruß, Bastian
Option Explicit
Private Sub UserForm_Initialize()
Dim lngZeile As Long
lngZeile = 11
Do
ListBox1.ColumnCount = 6
ListBox1.ColumnWidths = "0cm;2cm;4cm;2cm;2cm;3cm"
ListBox1.AddItem Cells(lngZeile, 1)
ListBox1.List(ListBox1.ListCount - 1, 1) = Cells(lngZeile, 2)
ListBox1.List(ListBox1.ListCount - 1, 2) = Format(Cells(lngZeile, 3), "dd.mm.yyyy")
ListBox1.List(ListBox1.ListCount - 1, 3) = Format(Cells(lngZeile, 4), "hh:mm")
ListBox1.List(ListBox1.ListCount - 1, 4) = Format(Cells(lngZeile, 5), "hh:mm")
ListBox1.List(ListBox1.ListCount - 1, 5) = Cells(lngZeile, 6)
lngZeile = lngZeile + 1
Loop While Cells(lngZeile, 2) ""
End Sub
Private Sub CommandButton1_Click()
Call BubbleSortUp(0, ListBox1.ListCount - 1, 2)
End Sub
Private Sub CommandButton2_Click()
Call BubbleSortDown(0, ListBox1.ListCount - 1, 2)
End Sub
Function BubbleSortUp(lngLBound As Long, lngUBound As Long, bytSpalte As Byte)
Dim j As Long
Dim i As Long
Dim k As Long
Dim vTemp As Variant
For j = lngUBound - 1 To lngLBound Step -1
' Alle links davon liegenden Zeichen auf richtige Sortierung
' der jeweiligen Nachfolger überprüfen:
For i = lngLBound To j
' Ist das aktuelle Element seinem Nachfolger gegenüber korrekt sortiert?
If CDate(ListBox1.List(i, bytSpalte)) > CDate(ListBox1.List(i + 1, bytSpalte)) Then
' Element und seinen Nachfolger vertauschen.
For k = 1 To 5
vTemp = ListBox1.List(i, k)
ListBox1.List(i, k) = ListBox1.List(i + 1, k)
ListBox1.List(i + 1, k) = vTemp
Next k
End If
Next i
Next j
End Function
Function BubbleSortDown(lngLBound As Long, lngUBound As Long, bytSpalte As Byte)
Dim j As Long
Dim i As Long
Dim k As Long
Dim vTemp As Variant
For j = lngUBound - 1 To lngLBound Step -1
' Alle links davon liegenden Zeichen auf richtige Sortierung
' der jeweiligen Nachfolger überprüfen:
For i = lngLBound To j
' Ist das aktuelle Element seinem Nachfolger gegenüber korrekt sortiert?
If CDate(ListBox1.List(i, bytSpalte))