VBA Removing ListBox Duplicates

不想你离开。 提交于 2019-12-11 05:03:35

问题


I'm trying to add a list of names from another worksheet that has duplicates. On the listbox, I want to have unique names, instead of duplicates. The following code is not sorting them for duplicates, it errors out. Any help is appreciated.

Dim intCount As Integer
Dim rngData As Range
Dim strID As String
Dim rngCell As Range
dim ctrlListNames as MSForms.ListBox
Set rngData = Application.ThisWorkbook.Worksheets("Names").Range("A").CurrentRegion

'declare header of strID and sort it
strID = "Salesperson"
rngData.Sort key1:=strID, Header:=xlYes
'Loop to add the salesperson name and to make sure no duplicates are added
For Each rngCell In rngData.Columns(2).Cells
    If rngCell.Value <> strID Then
        ctrlListNames.AddItem rngCell.Value
        strID = rngCell.Value
    End If
Next rngCell

回答1:


Way 1

Use this to remove the duplicates

Sub Sample()
    RemovelstDuplicates ctrlListNames
End Sub

Public Sub RemovelstDuplicates(lst As msforms.ListBox)
    Dim i As Long, j As Long
    With lst
        For i = 0 To .ListCount - 1
            For j = .ListCount - 1 To (i + 1) Step -1
                If .List(j) = .List(i) Then
                    .RemoveItem j
                End If
            Next
        Next
    End With
End Sub

Way 2

Create a unique collection and then add it to the listbox

Dim Col As New Collection, itm As Variant

For Each rngCell In rngData.Columns(2).Cells
    On Error Resume Next
    Col.Add rngCell.Value, CStr(rngCell.Value)
    On Error GoTo 0
Next rngCell

For Each itm In Col
    ctrlListNames.AddItem itm
Next itm



回答2:


Private Sub Workbook_Open()
Dim ctrlListNames As MSForms.ListBox
Dim i As Long
Dim j As Long

ctrlListNames.List = Application.ThisWorkbook.Worksheets("Names").Range("Salesperson").Value


With ctrlListNames
For i = 0 To .ListCount - 1
    For j = .ListCount To (i + 1) Step -1
        If .List(j) = .List(i) Then
            .RemoveItem j
        End If
    Next
Next
End With


End Sub

And it says invalid property array index.



来源:https://stackoverflow.com/questions/39129572/vba-removing-listbox-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!