【问题标题】:Excel (VBA) - UserForm Combobox > Listbox, stop duplicatesExcel (VBA) - 用户窗体组合框 > 列表框,停止重复
【发布时间】:2018-09-27 10:17:42
【问题描述】:

从组合框中选择类别后,列表框会更新,仅包含与组合框选择相关的记录。然而,该列表产生了重复,我想知道如何防止这种情况发生。

Private Sub ProdComp_Change()
Dim RowMax As Integer
Dim ws As Worksheet
Dim countexit As Integer
Dim cellcombo2 As String
Dim i As Integer

Set ws = ThisWorkbook.Sheets("products")
RowMax = ws.Cells(Rows.Count, "B").End(xlUp).Row

Me.LBType.Clear

With LBType
    For i = 2 To RowMax
        If ws.Cells(i, "B").Value = ProdComp.Text Then
        .AddItem ws.Cells(i, "c").Value
        Else
        End If
    Next i
End With

End Sub

Worksheet View

UserForm View

【问题讨论】:

  • 请举一些例子。另外,您确定 B 列中没有重复项吗?
  • 我添加了两张图片,如您所见,因为每种产品都有不同的变体,我想要防止发生的情况是您可以在“用户窗体视图”中看到让每种产品类型只显示一次而不是多次展示。但是,由于它目前的设计需要适应任何新添加的内容。

标签: vba excel


【解决方案1】:

尝试将项目添加到唯一的集合,然后将该集合添加到列表框。这样你就不会得到任何重复。

试试这个

Private Sub ProdComp_Change()
    '~~> when working with Rows, Please do not use `Integer`. Use `Long`
    Dim RowMax As Long, countexit As Long, i As Long
    Dim ws As Worksheet
    Dim cellcombo2 As String
    Dim col As New Collection, itm As Variant

    Set ws = ThisWorkbook.Sheets("products")
    RowMax = ws.Cells(Rows.Count, "B").End(xlUp).Row

    For i = 2 To RowMax
        If ws.Cells(i, "B").Value = ProdComp.Text Then
            '~~> On error resume next will
            '~~> create a unique collection
            On Error Resume Next
            col.Add ws.Cells(i, "c").Value, CStr(ws.Cells(i, "c").Value)
            On Error GoTo 0
        End If
    Next i

    Me.LBType.Clear

    If col.Count > 0 Then
        For Each itm In col
            LBType.AddItem itm
        Next
    End If
End Sub

如果数据过多,则可以将数据复制到数组中,而不是遍历行然后创建唯一集合。

【讨论】:

    【解决方案2】:

    你可以试试这个...

    Private Sub ProdComp_Change()
    Dim RowMax As Integer
    Dim ws As Worksheet
    Dim countexit As Integer
    Dim cellcombo2 As String
    Dim i As Integer
    Dim dict
    
    Set ws = ThisWorkbook.Sheets("products")
    RowMax = ws.Cells(Rows.Count, "B").End(xlUp).Row
    Set dict = CreateObject("Scripting.Dictionary")
    
    Me.LBType.Clear
    
    With LBType
        For i = 2 To RowMax
            If ws.Cells(i, "B").Value = ProdComp.Text Then
                dict.Item(ws.Cells(i, "c").Value) = ""
            End If
        Next i
        If dict.Count > 0 Then .List = dict.keys
    End With
    End Sub
    

    【讨论】:

    • 效果很好!谢谢,我一直在想如何正确地做到这一点!
    • @R.Langdell 不客气!很高兴它按预期工作。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多