Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong item removed from Listbox

Tags:

excel

vba

Items are transferred from ListBox1 to any of the 12 Listboxes (2-13), after items are selected and corresponding buttons are clicked. Listboxes (2-13) can’t contain more than 8 items.

Problem: If items are selected from the middle of Listbox1 the code leaves the last selected item in Listbox1 and erroneously removes the top item from Listbox1 that wasn’t selected. I’m not sure why. Please see screen shot and the code below:

Selected items in ListBox1:

enter image description here

Outcome after 'left arrow' button is pressed:(testtwo.A.2F item has disappeared and testseven.A.2R item remains in ListBox1.

enter image description here

Code for 'left' and 'right' buttons:

Private Sub BTN_MoveSelectedRight_Click()

    Dim iCtr As Long

    For iCtr = 0 To Me.ListBox2.ListCount - 1
        If Me.ListBox2.Selected(iCtr) = True Then
            Me.ListBox1.AddItem Me.ListBox2.List(iCtr)
        End If
    Next iCtr

    For iCtr = Me.ListBox2.ListCount - 1 To 0 Step -1
        If Me.ListBox2.Selected(iCtr) = True Then
            Me.ListBox2.RemoveItem iCtr
        End If
    Next iCtr



End Sub
Private Sub BTN_MoveSelectedLeft_Click()

   Dim iCtr As Long
   Dim i As Long
   Dim j As Long
   Dim arr(8) As Long

        For iCtr = 0 To Me.ListBox1.ListCount - 1

            If Me.ListBox1.Selected(iCtr) = True And Not ListBox2.ListCount = 8 Then
                Me.ListBox2.AddItem Me.ListBox1.List(iCtr)
                i = i + 1
                arr(i) = iCtr
            End If

          If i = 8 Then Exit For
        Next iCtr

        For j = i - 1 To 0 Step -1
         Me.ListBox1.RemoveItem arr(j)
        Next

End Sub

Listbox1 is fmMultiSelectExtended and Listboxes 2-13 are fmMultiSelectMulti.

Thank you.

like image 788
user3781528 Avatar asked May 06 '26 02:05

user3781528


1 Answers

I think the problem is with this line:

   For j = i - 1 To 0 Step -1

It doesn't look like it should be decremented as it's accessing arr not the list. Try:

   For j = i To 1 Step -1
like image 138
Doug Glancy Avatar answered May 09 '26 16:05

Doug Glancy