Visual Basic > Forms
Return the selected contents of a multiselect list box
Return the selected contents of a multiselect list box Below are two routines to retrieve the contents of a multiselect list box. One version is faster as it uses an API call, the other just uses properties exposed by the listbox: Option Explicit Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long 'Purpose : Returns an Array containing the selected items in a list box 'Inputs : lbGetItems The listbox to obtain the selected items from 'Outputs : Returns the number of select items. ' asSelectedItems() A string array (1 to NumItems). Where NumItems is the number of items currently selected 'Notes : Uses API calls and is faster than ListBoxSelectedItems2 Function ListBoxSelectedItems(lbGetItems As ListBox, asSelectedItems() As String) As Long Dim alIndexes() As Long, lThisItem As Long Const LB_GETSELITEMS As Long = &H191 ListBoxSelectedItems = lbGetItems.SelCount 'Determine the number of select items If ListBoxSelectedItems Then 'Fill an array with the index numbers of all the selected items ReDim alIndexes(ListBoxSelectedItems - 1) ReDim asSelectedItems(1 To ListBoxSelectedItems) Call SendMessage(lbGetItems.hwnd, LB_GETSELITEMS, ListBoxSelectedItems, alIndexes(0)) 'Populate the array with the listbox items For lThisItem = 0 To ListBoxSelectedItems - 1 asSelectedItems(lThisItem + 1) = lbGetItems.List(alIndexes(lThisItem)) Next Else 'Clear the result array Erase asSelectedItems End If End Function 'Purpose : Returns an Array containing the selected items in a list box 'Inputs : lbGetItems The listbox to obtain the selected items from 'Outputs : Returns the number of select items. ' asSelectedItems() A string array (1 to NumItems). Where NumItems is the number of items currently selected ''Notes : Doesn't use API calls (slower than ListBoxSelectedItems2) Function ListBoxSelectedItems2(lbGetItems As ListBox, asSelectedItems() As String) As Long Dim lThisItem As Long, lItemsStored As Long ListBoxSelectedItems2 = lbGetItems.SelCount 'Determine the number of select items If ListBoxSelectedItems2 Then ReDim asSelectedItems(1 To ListBoxSelectedItems2) 'Populate the array with the listbox items For lThisItem = 0 To lbGetItems.ListCount - 1 'Test if item is selected If lbGetItems.Selected(lThisItem) Then lItemsStored = lItemsStored + 1 'Item is selected, store it in the result array asSelectedItems(lItemsStored) = lbGetItems.List(lThisItem) End If If lItemsStored = ListBoxSelectedItems2 Then 'Retrieved all the selected item Exit For End If Next Else 'Clear the result array Erase asSelectedItems End If End Function
Visual Basic Codes
ActiveX
Miscellaneous
Applications
Code Snippets
Common Dialogs
Special Effects
Database Stuff
Date Time
Files Drives
Forms
Graphics Games
Internet Stuff
Multimedia
Other
Strings
Windows