Excel VBA将选择项从列表框移动到另一个弹出用户窗体的另一种形式的列表框中

时间:2015-04-14 19:22:29

标签: excel-vba userform vba excel

我有一个工作簿,其中包含一个人们可以选择多行的列表框。我想将一旦选中的信息带到另一个ListBox中,这个新表单将在选中时弹出。

我找到了在同一个用户窗体中的列表框之间进行转换的示例,但我需要帮助在不同的窗体之间移动它们。

此代码显示如何在同一表单上的两个用户表单之间传递信息。但我需要修改它以在两种不同的形式之间移动它。就像你点击一个提交按钮,然后弹出另一个带有文本框的列表框。

Option Explicit
'Move Listbox Items in UserForm
'code from Dave Peterson
'posted on www.contextures.com


    Private Sub BTN_moveAllLeft_Click()

    Dim iCtr As Long

    For iCtr = 0 To Me.ListBox2.ListCount - 1
        Me.ListBox1.AddItem Me.ListBox2.List(iCtr)
    Next iCtr

    Me.ListBox2.Clear
End Sub


Private Sub BTN_moveAllRight_Click()

Dim iCtr As Long

For iCtr = 0 To Me.ListBox1.ListCount - 1
    Me.ListBox2.AddItem Me.ListBox1.List(iCtr)
Next iCtr

Me.ListBox1.Clear
End Sub


Private Sub BTN_MoveSelectedLeft_Click()

Dim iCtr As Long

For iCtr = 0 To Me.ListBox2.ListCount - 1
    If Me.ListBox2.Selected(iCtr) = True Then
        Me.ListBox1.AddItem Me.ListBox2.List(iCtr)
    End If
Next iCtr

For iCtr = Me.ListBox2.ListCount - 1 To 0 Step -1
    If Me.ListBox2.Selected(iCtr) = True Then
        Me.ListBox2.RemoveItem iCtr
    End If
Next iCtr

End Sub


Private Sub BTN_MoveSelectedRight_Click()

Dim iCtr As Long

For iCtr = 0 To Me.ListBox1.ListCount - 1
    If Me.ListBox1.Selected(iCtr) = True 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 Then
        Me.ListBox1.RemoveItem iCtr
    End If
Next iCtr

End Sub

Private Sub cmdOK_Click()
Unload Me
End Sub

Private Sub UserForm_Initialize()

Dim iCtr As Long

With Me.ListBox1
    For iCtr = 1 To 10
        .AddItem "This is a test" & iCtr
    Next iCtr
End With

With Me.ListBox2
    For iCtr = 1 To 10
        .AddItem "This is a not a test" & iCtr
    Next iCtr
End With

Me.ListBox1.MultiSelect = fmMultiSelectMulti
Me.ListBox2.MultiSelect = fmMultiSelectMulti

End Sub

1 个答案:

答案 0 :(得分:0)

无论您在哪里看到Me,都可以引用不同的用户形式。

例如,我有两个用户表单UserForm1UserForm2。让我们说我们的初始ListBox,ListBox1UserForm1上,并包含颜色列表。 UserForm1还包含一个命令按钮CommandButton1,该按钮会将UserForm1中的所选项目移动到ListBox1中的另一个列表框(也称为UserForm2)到下一个形式。

UserForm1中的代码,显示的初始表单,命令按钮上的代码如下所示:

Private Sub CommandButton1_Click()

    Dim i As Integer

    For i = 0 To Me.ListBox1.ListCount - 1
        If Me.ListBox1.Selected(i) = True Then
            UserForm2.ListBox1.AddItem Me.ListBox1.List(i)
        End If
    Next i

    UserForm2.Show


End Sub