【问题标题】:Multiple ListBox selection avoiding duplicates VBA多个列表框选择避免重复 VBA
【发布时间】:2015-01-23 11:34:21
【问题描述】:

我正在构建一个包含两个 ListBox 的用户窗体,以便用户可以从 ListBox1 中选择选项并将它们添加到 ListBox2 或从 ListBox2 中删除选项

我正在努力解决的是如何防止将重复项添加到 ListBox2 中?本质上,我想构建一个函数(?)来检查一个选项是否已经包含在 ListBox2 中

Private Sub CommandButton3_Click()

'### Adds Items from ListBox1 to ListBox2
For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) = True Then ListBox2.AddItem ListBox1.List(i)
Next i

ListBox1.Selected

End Sub

Private Sub CommandButton4_Click()

'### Removes Items from ListBox2
Dim counter As Integer
counter = 0

For i = 0 To ListBox2.ListCount - 1
    If ListBox2.Selected(i - counter) Then
        ListBox2.RemoveItem (i - counter)
        counter = counter + 1
    End If
Next i

End Sub

【问题讨论】:

  • 使用包含函数添加检查
  • 请发布您的图片链接...
  • 不确定包含函数如何在 VBA 中工作。但是,我在 stackoverflow 上发现了另一个类似的线程,它解决了类似的问题并努力根据我的需要进行调整:stackoverflow.com/questions/19755920/…

标签: vba listbox userform


【解决方案1】:

下面的代码可以解决这个问题:

Private Sub CommandButton3_Click()

For i = 0 To ListBox1.ListCount - 1

    If ListBox1.Selected(i) = True Then
        valCheck (ListBox1.List(i))
    End If

Next i

End Sub

Private Function valCheck(str As String)

'### Adds Items from ListBox1 to ListBox2

Dim valExists As Boolean

    valExists = False


        For i = 0 To ListBox2.ListCount - 1

            If ListBox2.List(i) = str Then
                valExists = True
            End If

        Next i

        If valExists Then
            MsgBox ("already exists")
        Else
            ListBox2.AddItem str
        End If





End Function
Private Sub CommandButton4_Click()

'### Removes Items from ListBox2

For i = 0 To ListBox2.ListCount - 1

    If ListBox2.Selected(i) = True Then ListBox2.RemoveItem (i)

Next i



End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多