2015-12-21 55 views
1

我想將不超過8個選定項目從列表框1移動到列表框2。兩個列表框都是多選的。當我選擇多於8個項目並將它們一次移動到Listbox2時,這些項目不會從Listbox1中刪除。但是,如果我不嘗試限制可移動項目的數量,但我將其從ListBox1中移除時,將單獨移除它們(項目編號爲8的項目除外)。限制可以從一個列表框移動到另一個列表框的項目數量

如果我不嘗試限制可移動的項目數很難讓它與指定的條件一起工作(Listbox2中只有8個項目)。

我環顧四周,但找不到一個好例子。我真的很感謝建議。我也想知道我想要做的是不是可能的。

Private Sub BTN_MoveSelectedRight_Click() 

    Dim iCtr 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) 

      End If 

     Next iCtr 

     For iCtr = Me.ListBox1.ListCount - 1 To 0 Step -1 
      If Me.ListBox1.Selected(iCtr) = True And Not ListBox2.ListCount = 8 Then 
       Me.ListBox1.RemoveItem iCtr 

      End If 
     Next iCtr 


End Sub 

回答

0

此代碼將ListBox1的前8個所選的項目移至listbox2如果listbox2有8個項目將什麼都不做,我不知道這是否是你所需要的。

Private Sub BTN_MoveSelectedRight_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) 

       arr(i) = iCtr 
       i = i + 1 
      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 
1

ListBox.ListCount返回您的Listox中的物品數量。如果你想獲得所選項目的數量,那麼你需要這種功能:

Private Function SelectedCount(lbox As msforms.ListBox) As Integer 
    Dim i As Integer 
    Dim sel As Integer 

    For i = 0 To lbox.ListCount - 1 
     If lbox.Selected(i) Then sel = sel + 1 
    Next 

    SelectedCount = sel 
End Function 

如果你願意,你可以跟蹤選擇的並且每當用戶選擇的第九項,取消選擇最舊的項目。這樣你的ListBox將始終有八個(或更少)最近選擇的項目。你可以這樣做:

Option Explicit 
Private mEnableUserEvents As Boolean 
Private mSelectionOrder As Collection 
Private Sub ListBox1_Change() 
    Dim key As String 

    If Not mEnableUserEvents Then Exit Sub 
    key = CStr(ListBox1.ListIndex) 
    If ListBox1.Selected(ListBox1.ListIndex) Then 
     mSelectionOrder.Add ListBox1.ListIndex, CStr(ListBox1.ListIndex) 
     If mSelectionOrder.Count = 9 Then 
      mEnableUserEvents = False 
      ListBox1.Selected(mSelectionOrder.Item(1)) = False 
      mEnableUserEvents = True 
      mSelectionOrder.Remove 1 
     End If 
    Else 
     mSelectionOrder.Remove key 
    End If 
End Sub 

Private Sub UserForm_Initialize() 
    mEnableUserEvents = True 
    Set mSelectionOrder = New Collection 
End Sub 
相關問題