【问题标题】:Move selected items multiple rows to another list Excel vba将所选项目多行移动到另一个列表 Excel vba
【发布时间】:2016-03-04 10:50:48
【问题描述】:

我有一个包含多个(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

希望能帮到你。我总是收到缺少对象的错误消息。 最好的问候

马蒂亚斯

【问题讨论】:

  • 能否请您提供excel文件?谢谢。
  • 我已经完全使用了您的代码,并且它对我有用。您确定您的目标是正确的 ListBox?
  • 您好 Robert 我总是收到错误消息运行时错误 424“需要对象”。那我就不上班了。这附加为第一个 me.ListBox2.list...

标签: vba excel listbox


【解决方案1】:

如果要将项目从 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

最好的问候

【讨论】:

    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2012-10-31
    • 2013-11-05
    相关资源
    最近更新 更多