VBA 列表框列/字段的组合框列表中的唯一值

VBA Unique values in Combobox list from Listbox column / field

每次列表框的列表发生变化时,我希望使组合框只列出列表框字段/列中的唯一值。

例如,列表框中的第 3 列包含 Apple、Strawberry 和 Banana 的多个实例。我希望组合框只包含苹果、草莓和香蕉各一次。

有什么好点子吗?

可以使用字典从列表中删除重复项。要使以下代码正常工作,您必须将“Microsoft Scripting Runtime”添加到 references.

Private Sub ListBox1_Change()
    Dim dict As Scripting.Dictionary
    Set dict = New Scripting.Dictionary
    Dim i As Long
    On Error Resume Next
    For i = 0 To ListBox1.ListCount - 1
        dict.Add Key:=ListBox1.List(i), Item:=0
    Next i
    ComboBox1.List = dict.Keys
End Sub

我还没有机会测试它,如果它有效,请告诉我。

试试下面的代码,让我们知道您的反馈。

Private Sub ListBox1_Change()
    Dim dict As Object
    Dim i As Long

    Set dict = CreateObject("Scripting.Dictionary")
        For i = 0 To ListBox1.ListCount - 1
            dict.Item(ListBox1.List(i)) = vbNullString
        Next i
    ComboBox1.List = dict.keys
    Set dict = Nothing
End Sub

将唯一的第 3 列项目分配给 Combobox

  • [1] 有几种方法可以接收uniques (dictionary, arraylist);我演示了一种使用 FilterXML() 函数(自 vers. 2013+ 起可用)的方法,以及一种通过列表框的 [=13= 隔离 3rd 列表框列 的棘手方法] 属性 通过 arr = Application.Index(Me.ListBox1.Column, 3, 0),从而接收到一个没有循环的“平面”数组,
  • [2] 基于数组数据创建一个简单的格式良好的 xml 结构并提供 XPath搜索字符串以获得唯一性和
  • [3] 将通过 FilterXML() 收到的“垂直”2-dim uniques 分配给组合框的 .List 属性。此外,我添加了一个小错误处理程序,用于处理单个项目的情况。
Private Sub ListBox1_Change()
    If Me.ListBox1.ListCount = 0 Then Exit Sub              ' Escape if no list items available
    With Application
        '[1] get 3rd column items of listbox
        Dim arr: arr = .Index(Me.ListBox1.Column, 3, 0)     ' Index uses 1-based indices

        '[2] create FilterXML arguments to get uniques
        Dim XContent As String: XContent = "<t><s>" & Join(arr, "</s><s>") & "</s></t>"
        Dim XP As String: XP = "//s[not(preceding::*=.)]"   ' XPath expression searching uniques
        '[3] assign "vertical" 2-dim uniques to combobox
        Dim uniques: uniques = .FilterXML(XContent, XP)     ' get uniques to combobox
        On Error Resume Next:  Me.ComboBox1.List = uniques  ' assign uniques to combobox
        If Err.Number <> 0 Then Me.ComboBox1.AddItem uniques
    End With
End Sub