VBA 删除列表框重复项

VBA Removing ListBox Duplicates

我正在尝试从另一个有重复项的工作表中添加姓名列表。在列表框中,我想要唯一的名称,而不是重复的名称。下面的代码没有对它们进行重复排序,它出错了。感谢任何帮助。

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

方式一

使用它来删除重复项

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

方式二

创建一个独特的集合,然后将其添加到列表框

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
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

它说 属性 数组索引无效。

它说 属性 数组索引无效,因为删除条目后列表变短了。如果我们使用 FOR,结束值是静态的,因此,我们需要使用 DO while 循环。使用以下代码删除重复项。

Count = ListBox1.ListCount - 1

i = 0
j = 0

Do While i <= Count
j = i + 1
Do While j <= Count
If ListBox1.List(i) = ListBox1.List(j) Then
ListBox1.RemoveItem (j)
Count = ListBox1.ListCount - 1  'Need to update list count after each removal. 
End If
j = j + 1
Loop
i = i + 1
Loop