从列表框中删除了错误的项目

时间:2016-01-02 17:11:07

标签: excel-vba vba excel

在选择项目并单击相应按钮后,项目将从ListBox1传输到12个列表框中的任何一个(2-13)。列表框(2-13)不能包含超过8个项目。

问题:如果从Listbox1的中间选择了项目,则代码将保留Listbox1中的最后一个选定项目,并错误地从Listbox1中删除未选中的顶部项目。我不知道为什么。请参阅屏幕截图和下面的代码:

ListBox1中的所选项目:

enter image description here

左箭头后的结果'按下按钮:( testtwo.A.2F项目已消失,testseven.A.2R项目仍保留在ListBox1中。

enter image description here

'左'代码并且'对'按钮:

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是fmMultiSelectExtended,而Listboxes 2-13是fmMultiSelectMulti。

谢谢。

1 个答案:

答案 0 :(得分:3)

我认为问题在于这一行:

   For j = i - 1 To 0 Step -1

它看起来不应该递减,因为它正在访问arr而不是列表。尝试:

   For j = i To 1 Step -1