将所选项目多行移动到另一个列表Excel vba

时间:2016-03-04 10:50:48

标签: excel vba excel-vba listbox

我有一个包含多个(3列)所选项目的列表框,我想仅将所选项目移动到另一个列表框,但此列表框还应包含3列。 在选择新项目之前,我已使用以下代码将其他项目添加到listbox1:

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

我希望你能提供帮助。我总是收到对象丢失的错误消息。 最好的问候

的Matthias

1 个答案:

答案 0 :(得分:0)

如果要将项目从list1移动到另一个list2,可以使用vba中的columns属性。

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

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

祝你好运