removing multiple selected items in a listbox - code only recognising first selection

*爱你&永不变心* 提交于 2019-12-10 14:54:49

问题


I have two listboxes and am trying to add items from List 1 to List 2, and then be able to remove multiple items from List 2 at once. Note that List 1 stays stagnant (this is how it is supposed to be).

I have the adding items working right:

'Add the selected items to List 2
Dim i As Integer

If lst1.ItemsSelected.Count > 0 Then
    i = 0
    While i < lst1.ListCount
        If lst1.Selected(i) Then
            lst2.AddItem (lst1.ItemData(i) & ";" & lst1.Column(1, i) & ";")
            lst1.Selected(i) = False
        End If
        i = i + 1
    Wend
End If

However, when I try to remove the items from List 2 in a similar way, it only recognises the first selected item as selected and skips over the other items that I have selected. This is the problem. Here is my code:

'Remove the selected items from List 2
Dim i As Integer

If lst2.ItemsSelected.Count > 0 Then
    i = lst2.ListCount - 1
    While i >= 0
       If lst2.Selected(i) Then
           lst2.RemoveItem (i)
           lst2.Selected(i) = False
       End If
        i = i - 1
    Wend
End If

How can I get this working correctly?


回答1:


As far as I can tell, as soon as you remove one item, all items become unselected, so:

Dim itm As Variant
Dim srem As String
Dim asrem As Variant

    For Each itm In lst2.ItemsSelected
        srem = srem & "," & itm
    Next

    asrem = Split(Mid(srem, 2), ",")
    For i = UBound(asrem) To 0 Step -1
        lst2.RemoveItem lst2.ItemData(asrem(i))
    Next

Note also that this is Access and you are dealing with a value list, so Replace on the text of Row Source will also work.




回答2:


Try using a for/next loop instead of While?

Something like this works in PPT/XLS, should be similar in Access I think.

For i = lst2.ListCount - 1 to 0 step -1
    If lst2.Selected(i) = True Then
        lst2.RemoveItem(i)
    End If
Next



回答3:


Same Concept as @Fionnuala with the exception that I used a collection which I generally find more flexible:

Dim i As Integer
Dim listColl As Collection
Dim Item As Variant

Set listColl = New Collection
With Me.listAvailable
    ' Add Selected Items to Collection (MultiSelect Listbox)
     For i = 0 To .ListCount - 1
        If .Selected(i) Then
            listColl.Add .ItemData(i)
        End If
    Next i
End With

For Each Item In listColl
    Me.listSelected.AddItem Item
    Me.listAvailable.RemoveItem Item
Next Item


来源:https://stackoverflow.com/questions/14740649/removing-multiple-selected-items-in-a-listbox-code-only-recognising-first-sele

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!