MKoslof
07-31-2004, 06:20 PM
The following code will provide move up and move down functionality for a VBA ListBox. This works for all potential modes of list box selecting:
1) single select
2) Multi select (using the ctrl key)
3) Extended select (using the shift key)
Basically, it will take the selected item and move it up or move it down. So blocks of selected items will move succesfully, multiple selected items, etc.
I do not take full credit for writing this...Herilane also assisted. It was a tag team effort.
Private Sub cmd_Up_Click()
Dim i As Long
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String
pos = 0
For i = 0 To ListBox1.ListCount - 1
leaveAlone = False
If ListBox1.Selected(i) Then
If i = pos Then
leaveAlone = True
End If
pos = pos + 1
If leaveAlone = False Then
Temp = ListBox1.List(i - 1)
ListBox1.List(i - 1) = ListBox1.List(i)
ListBox1.List(i) = Temp
ListBox1.ListIndex = i - 1
ListBox1.Selected(i) = False
ListBox1.Selected(i - 1) = True
End If
End If
Next
End Sub
Private Sub cmd_Down_Click()
Dim i As Integer
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String
pos = ListBox1.ListCount - 1
For i = ListBox1.ListCount - 1 To 0 Step -1
leaveAlone = False
If ListBox1.Selected(i) Then
If i = pos Then
leaveAlone = True
End If
pos = pos - 1
If Not leaveAlone Then
Temp = ListBox1.List(i + 1)
ListBox1.List(i + 1) = ListBox1.List(i)
ListBox1.List(i) = Temp
ListBox1.ListIndex = i + 1
ListBox1.Selected(i) = False
ListBox1.Selected(i + 1) = True
End If
End If
Next
End Sub
1) single select
2) Multi select (using the ctrl key)
3) Extended select (using the shift key)
Basically, it will take the selected item and move it up or move it down. So blocks of selected items will move succesfully, multiple selected items, etc.
I do not take full credit for writing this...Herilane also assisted. It was a tag team effort.
Private Sub cmd_Up_Click()
Dim i As Long
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String
pos = 0
For i = 0 To ListBox1.ListCount - 1
leaveAlone = False
If ListBox1.Selected(i) Then
If i = pos Then
leaveAlone = True
End If
pos = pos + 1
If leaveAlone = False Then
Temp = ListBox1.List(i - 1)
ListBox1.List(i - 1) = ListBox1.List(i)
ListBox1.List(i) = Temp
ListBox1.ListIndex = i - 1
ListBox1.Selected(i) = False
ListBox1.Selected(i - 1) = True
End If
End If
Next
End Sub
Private Sub cmd_Down_Click()
Dim i As Integer
Dim leaveAlone As Boolean
Dim pos As Long
Dim Temp As String
pos = ListBox1.ListCount - 1
For i = ListBox1.ListCount - 1 To 0 Step -1
leaveAlone = False
If ListBox1.Selected(i) Then
If i = pos Then
leaveAlone = True
End If
pos = pos - 1
If Not leaveAlone Then
Temp = ListBox1.List(i + 1)
ListBox1.List(i + 1) = ListBox1.List(i)
ListBox1.List(i) = Temp
ListBox1.ListIndex = i + 1
ListBox1.Selected(i) = False
ListBox1.Selected(i + 1) = True
End If
End If
Next
End Sub