gpt4 book ai didi

VBA 删除列表框重复项

转载 作者:行者123 更新时间:2023-12-04 21:15:51 25 4
gpt4 key购买 nike

我正在尝试从另一个具有重复项的工作表中添加名称列表。在列表框上,我希望有唯一的名称,而不是重复的。以下代码不会对它们进行重复排序,它会出错。任何帮助表示赞赏。

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

关于VBA 删除列表框重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39129572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com