Moving items in a List Box

Often, the order of items in a list is important. The example in this section demonstrates how to allow the user to move items up or down in a ListBox. The VBE uses this type of technique to let you control the tab order of the items in a UserForm (right-click a UserForm and choose Tab Order from the shortcut menu).

Figure 14-13 shows a dialog box that contains a ListBox and two CommandButtons. Clicking the Move Up butto! moves the selected item up in the ListBox; clicking the Move Down button moves the selected item down.

Figure 14-13: The buttons allow the user to move items up or down in the ListBox. CD-ROM

This example, named listbox move items.xlsm , is available on the companion CD-ROM.

The event handler procedures for the two CommandButtons follow:

Private Sub MoveUpButton_Click()

if ListBoxl.Listindex <= 0 Then Exit Sub Numitems = ListBoxl.ListCount Dim TempList()

ReDim TempList(0 To Numitems - l) ' Fill array with list box items For i = 0 To Numitems - l

TempList(i) = ListBoxl.List(i) Next i ' Selected item itemNum = ListBoxl.Listindex ' Exchange items

Tempitem = TempList(itemNum) TempList(itemNum) = TempList(itemNum - l) TempList(itemNum - l) = Tempitem ListBoxl.List = TempList ' Change the list index

ListBoxl.Listindex = itemNum - l End Sub

Private Sub MoveDownButton_Click()

if ListBoxl.Listindex = ListBoxl.ListCount - l Then Exit Sub Numitems = ListBoxl.ListCount Dim TempList()

ReDim TempList(0 To Numitems - l) ' Fill array with list box items For i = 0 To Numitems - l

TempList(i) = ListBoxl.List(i) Next i ' Selected item itemNum = ListBoxl.Listindex

' Exchange items

TempItem = TempList(ItemNum) TempList(ItemNum) = TempList(ItemNum + 1) TempList(ItemNum + 1) = TempItem ListBox1.List = TempList ' Change the list index

ListBox1.ListIndex = ItemNum + 1 End Sub

These procedures work fairly well, but you'll find that, for some reason, relatively rapid clicking doesn't always register. For example, you may click the Move Down button three times in quick succession, but the item only moves one or two positions. The solution is to add a new DblClick event handler for each CommandButton. These procedures, which simply call the Click procedures, are as follows:

Private Sub MoveUpButton_DblClick _

(ByVal Cancel As MSForms.ReturnBoolean) Call MoveUpButton_Click End Sub

Private Sub MoveDownButton_DblClick _

(ByVal Cancel As MSForms.ReturnBoolean) Call MoveDownButton_Click End Sub

+1 -1

Responses

Post a comment