Set the ListIndex Without the Click Event

Set the ListIndex Without the Click Event

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:

 	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 LongPublic 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 IfEnd Function
See also  5 Tips for Working With an Onsite Interpreter

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist