MrPatterns
MrPatterns

Reputation: 4434

Given the tabindex (integer) how do I select a listbox?

I made a form with 10 listboxes. I want to give focus to a listbox of my choosing. For example, if i choose the integer "3" it will put focus on the listbox whose tabindex = 3.

How do I do this?

I thought this might work but it doesn't:

Dim lst As VB.ListBox: Set lst = Form.Controls(lst.TabIndex = 3)
lst.SetFocus

Upvotes: 0

Views: 644

Answers (1)

George Mastros
George Mastros

Reputation: 24498

Do you have a control array for your list boxes? If so, you can simply do this:

YourListBoxName.Item(YourNumber).SetFocus

The above code will only work properly for you if the List boxes are a control array and you have the tab indexes set in the same order that you placed the list boxes on the screen.

Otherwise, you can try this code:

Dim oControl As Control
Dim YourNumber As Integer

YourNumber = 4

For Each oControl In Me.Controls
    If oControl.TabIndex = YourNumber Then
        oControl.SetFocus
        Exit For
    End If
Next

This code will loop through all the controls on your form and actively search for the one that matches your tab index. Once the control is found, it sets the focus to it.

Upvotes: 1

Related Questions