vba userform中添加按钮的功能

时间:2014-01-16 06:53:29

标签: vba userform

我有两个列表框.Listbox_1显示食物项目列表,listbox_2为空。单击按钮后,box1中的所选项目应移至box2。我不知道从哪里开始。谁能帮我?

3 个答案:

答案 0 :(得分:1)

示例代码(stackoverflow.com/questons/19064043/...)的第15行和第16行之间,

插入此行。

   .RemoveItem(i)

例如

Private Sub UserForm_Initialize()
    '~~> Adding Sample Data to listbox 1
    ListBox1.List = ThisWorkbook.Sheets(1).Range("A1:E3").Value
End Sub

Private Sub CommandButton1_Click()
    Dim iIndex
    Dim i As Long, j As Long, k As Long

    With ListBox1
        i = .ListIndex

        ListBox2.AddItem .List(i, 0)

        j = ListBox2.ListCount - 1

        For k = 1 To .ColumnCount - 1
            ListBox2.List(j, k) = .List(i, k)
        Next k

        .RemoveItem(i)

    End With
End Sub

答案 1 :(得分:1)

列表框保留带索引号的值。

在CommandButtom_Click上,使用 ListBox.ListIndex 访问该值的索引。

然后访问该索引的值并将值放入其他列表中。在第二个列表中添加该值后,使用该索引号从第一个列表中删除值。

我只是给你一个方向,我希望它会对你有帮助。

答案 2 :(得分:1)

    Ok!! I am updating the above answer of Mr. Maco.

Private Sub UserForm_Initialize()
    '~~> Adding Sample Data to listbox 1
    ListOne.List = ThisWorkbook.Sheets(1).Range("A1:A8").Value 'Here ListOne is the name of ListBox1
End Sub

Private Sub CommandButton1_Click()
    Dim iIndex
    Dim i As Long, j As Long, k As Long

    With ListBox1
        i = ListOne.ListIndex

        ListTwo.AddItem ListOne.List(i, 0) 'ListTwo is the name of ListBox2

        j = ListTwo.ListCount - 1

        For k = 1 To ListOne.ColumnCount - 1
            ListTwo.List(j, k) = .List(i, k)
        Next k

        ListOne.RemoveItem (i) ' Add here the reference Name i.e. ListOne

    End With
End Sub

I hope, this should work for you.