Debug.Print SetListIndex(List1, 9)
'If an error occurred (if there were only eight elements, for example),' the previous 'index value is returned. Code the SetListIndex function in a standard 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 Public Function SetListIndex(lst As Control, _ ByVal NewIndex As Long) As Long Const CB_GETCURSEL = &H147 Const CB_SETCURSEL = &H14E Const LB_SETCURSEL = &H186 Const LB_GETCURSEL = &H188 If TypeOf lst Is ListBox Then Call SendMessage(lst.hWnd, _ LB_SETCURSEL, NewIndex, 0&) SetListIndex = SendMessage(lst.hWnd, _ LB_GETCURSEL, NewIndex, 0&) ElseIf TypeOf lst Is ComboBox Then Call SendMessage(lst.hWnd, _ CB_SETCURSEL, NewIndex, 0&) SetListIndex = SendMessage(lst.hWnd, _ CB_GETCURSEL, NewIndex, 0&) End If End Function If you set the ListIndex property of a list-box or combo-box control, VB might generate an unwanted Click event. Instead of writing code to bypass the Click event, use SendMessage to set the ListIndex without generating the event. Call the SetListIndex function below, passing the list (either a list box or combo box) and the desired new index value. SetListIndex attempts to set the value and returns the current index so you can confirm whether your request "took." For example, this code should set the index to the tenth element: |