In un form aggiungiamo il ListBox con nome ListBox1 e 4 bottoni con nome cmdUp, cmdDown, cmdAdd, cmdRemove.
1: Private Sub cmdAdd_Click()
2: ' aggiunge un nuovo elemento
3: ListBox1.AddItem "Item " & CStr(ListBox1.ListCount + 1)
4: End Sub
5:
6: Private Sub cmdRemove_Click()
7: ' rimuove un elemento
8: If ListBox1.ListIndex > -1 Then
9: ListBox1.RemoveItem ListBox1.ListIndex
10: End If
11: End Sub
12:
13: Private Sub cmdUp_Click()
14: Dim sText As String
15: Dim iIndex As Integer
16:
17: ' verifica se solo un elemento è selezionato
18: If ListBox1.SelCount = 1 Then
19: If ListBox1.ListIndex = 0 Then Exit Sub
20:
21: ' salva l'elemento da spostare
22: sText = ListBox1.List(ListBox1.ListIndex)
23: iIndex = ListBox1.ListIndex
24:
25: ' rimuove l'elemento
26: ListBox1.RemoveItem ListBox1.ListIndex
27:
28: ' aggiunge l'elemento una posizione più in alto
29: ListBox1.AddItem sText, iIndex - 1
30:
31: ' viene selezionato l'elemento spostato
32: ListBox1.Selected(iIndex - 1) = True
33: End If
34: End Sub
35:
36: Private Sub cmdDown_Click()
37: Dim sText As String
38: Dim iIndex As Integer
39: ' verifica se solo un elemento è selezionato
40: If ListBox1.SelCount = 1 Then
41: If ListBox1.ListCount - 1 = ListBox1.ListIndex Then Exit Sub
42:
43: sText = ListBox1.List(ListBox1.ListIndex)
44: iIndex = ListBox1.ListIndex
45:
46: ListBox1.RemoveItem ListBox1.ListIndex
47: ListBox1.AddItem sText, iIndex + 1
48: ListBox1.Selected(iIndex + 1) = True
49: End If
50: End Sub