Home | What's New | Articles | Code Downloads | Tool Box | Links | Code Snippets  

List Box

Seeing Which Items Are Selected
When multiple selection is allowed in a ListBox, use a loop to see if the Selected property is true for each item

Dim i As Integer
  For i = 0 To List1.ListCount - 1
    If List1.Selected(i) Then
      MsgBox List1.List(i) & " is selected."
    End If
  Next I

Auto-searching a List Box 

This code finds the closest match to what is enter into a text box.

Enter this into the General Declarations of a form:

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

Private Const LB_FINDSTRING = &H18F

In the change event of a Text Box control enter:

'LB_FINDSTRING finds the string that matches most closely
        'SendMessage takes:
        '1) the hWnd of the list box
        '2)  the starting point for the search.  -1 is used to search the whole listbox
        '3)  a long pointer to the string to find
       lstBox.ListIndex = SendMessage(lstBox.hwnd, LB_FINDSTRING, -1, ByVal Text1.Text)

Rename lstBox to the name of your list box and Text1 to the name of the text box.

When you type in the text box the closest match will be selected in the list box.


Adding a horizontal scroll bar to a List Box 

Enter this into the General Declarations of a form or module:

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

Private Const LB_GETHORIZONTALEXTENT = &H193
Private Const LB_SETHORIZONTALEXTENT = &H194

Add this to the same form or module:

Public Property Let HorziontalScrollWidth(m_lstBox As ListBox, ScrollWidth As Long)
    SendMessage m_lstBox.hwnd, LB_SETHORIZONTALEXTENT, ScrollWidth, &O0
End Property

Public Property Get HorziontalScrollWidth(m_lstBox As ListBox) As Long
     HorziontalScrollWidth = SendMessage(m_lstBox.hwnd, LB_GETHORIZONTALEXTENT, &O0, &O0)
End Property

To set the width that the list box can scroll use:

HorziontalScrollWidth(myListBox) = 1000 ' Pixels

If the List box is less than 1000 pixels wide a scroll bar will be shown.

 


Finding the first visible item in List Box 

Enter this into the General Declarations of a form or module:

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

Private Const LB_GETTOPINDEX = &H18E

Add this to the same form or module:

Public Property Get FirstVisibleListItem(m_lstBox As ListBox) As Long
     FirstVisibleListItem = SendMessage(lstBox.hwnd, LB_GETTOPINDEX, &O0, &O0)
End Property

To find the first visible item in a list box use:

MsgBox FirstVisibleListItem(myListBox)