Excel UserForm将项添加到列表框并标记为选中

时间:2014-07-27 21:58:04

标签: excel listbox

在填充ListBox时,如何将项目标记为已选中?

For Ctr = LBound(MyArray) To UBound(MyArray)

If LB1 = MyArray(Ctr) Then
    UserForm1.ListBox1.AddItem MyArray(Ctr)   'Add item and mark as selected
Else
    UserForm1.ListBox1.AddItem MyArray(Ctr)   'Just add item
End If

Next

2 个答案:

答案 0 :(得分:2)

当您向ListBox添加新项目而未向varIndex指定可选的AddItem参数时,它会添加到列表的末尾。该项的索引为ListCount - 1ListBox项索引从0开始)。因此,要在添加后选择它,您需要执行以下操作:

UserForm1.ListBox1.Selected(UserForm1.ListBox1.ListCount - 1) = True

答案 1 :(得分:0)

' FROM MY UserForm_Initialize() SUB

Dim LB1 As String
 LB1 = Cells(RW, 8) 'DATA FROM COLUMN 8 IN THE SELECTED ROW PUT IN THE VARIABLE LB1
PopulateListBox (LB1)

'THE FUNCTION CALLED
 Private Function PopulateListBox(ByVal LB1)
'MsgBox LB1

Dim MyArray As Variant
Dim Ctr As Integer
Dim i As Integer

MyArray = Array("Yes", "No")
For Ctr = LBound(MyArray) To UBound(MyArray)

'IF LB1 MATCHES THE ARRAY ITEM, TAKE THAT ITEMS KEY (Ctr) AND PUT IN VARIABLE i

If LB1 = MyArray(Ctr) Then
    UserForm1.ListBox1.AddItem MyArray(Ctr)
    i = Ctr
    'MsgBox i
Else
    UserForm1.ListBox1.AddItem MyArray(Ctr)
End If
 Next
 'SHOW SELECTED LISTBOX ITEM BY ADDING i AS THE SELECTED LISTBOX ITEM'S KEY
 UserForm1.ListBox1.Selected(i) = True
End Function