2016-03-04 77 views
0

我有一个列表框中有多个(3列)选定的项目,我想只将选定的项目移动到另一个列表框,但此列表框也应包含3列。 之前选择新的项目,我已经添加了其他项目为ListBox此代码:将选定的项目多行移动到另一个列表Excel VBA

Private Sub UserForm_Initialize() 
     ListBox1.MultiSelect = 2 
     ListBox2.MultiSelect = 2 

      Dim RowsNumber As Integer 
      Dim RowsNumberOnly As Integer 
      Dim i As Integer 
      Dim Customers As Long 
      Dim customersloop As Long 
      Dim test As String 
      RowsNumber = FunctionCount.calculateRows 
       RowsNumberOnly = FunctionCount.calculateRowsValue 

      ListBox1.ColumnCount = 3 
      ListBox1.ColumnWidths = "50;50;50" 

      ListBox2.ColumnCount = 3 
      ListBox2.ColumnWidths = "50;50;50" 


Customers = 10 
i = 0 

For customersloop = Customers To RowsNumber 

    ListBox1.AddItem 
    ListBox1.List(i, 0) = Sheets("Test").Range("J" & customersloop).Value 
    ListBox1.List(i, 1) = Sheets("Test").Range("K" & customersloop).Value 
    ListBox1.List(i, 2) = Sheets("Test").Range("L" & customersloop).Value 
    i = i + 1 
    Next 



     End Sub 

之后所选择的项目需要转移到其他listbox2 这是我的代码:

Private Sub SelectItems_btn_Click() 
    Dim SelectedItems As String 
    Dim i As Integer 
    Dim ListBox2i As Integer 
ListBox2i = 0 
For i = 0 To ListBox1.ListCount - 1 

    If ListBox1.Selected(i) = True Then 

    Me.ListBox2.Additem 
    Me.ListBox2.List(ListBox2i, 0) = ListBox1.List(i, 0).Value 
    Me.ListBox2.List(ListBox2i, 1) = ListBox1.List(i, 1).Value 
    Me.ListBox2.List(ListBox2i, 2) = ListBox1.List(i, 2).Value 
    ListBox2i = ListBox2i + 1 
    End If 

Next 

End Sub 

我希望你能帮上忙。我总是收到错误消息,说明对象丢失了。 最好的问候

马蒂亚斯

+0

能否请您为我们提供了Excel文件? 谢谢。 –

+0

我已经使用了你的代码,它在我身边工作。你确定,你的目标是正确的列表框? –

+0

Hello Robert我总是收到错误消息运行时错误424“Object required”。然后我不会工作。这附加为第一个me.ListBox2.list ... – user24555

回答

0

如果你想从列表1项移动到另一个列表2,你可以使用列属性从VBA。

这是将值添加到我的第一个list1和3列后的解决方案代码。

Private Sub SelectItems_Click() 
Dim i As Integer 

For i = 0 To ListBox1.ListCount - 1 

    If ListBox1.Selected(i) = True Then 
    ListBox2.AddItem 
    ListBox2.Column(0, (ListBox2.ListCount - 1)) = ListBox1.Column(0, i) 
    ListBox2.Column(1, (ListBox2.ListCount - 1)) = ListBox1.Column(1, i) 
    ListBox2.Column(2, (ListBox2.ListCount - 1)) = ListBox1.Column(2, i) 

    End If 

Next 

End Sub 

问候

相关问题