如何从组合框中删除重复值| excel vba |

问题描述 投票:0回答:1

我有一种情况,我想将唯一值填充到组合框中,但不包括重复值

我的工作表详细信息

Sheet

代码:

Private Sub ComboBoxscname_DropButtonClick()
    With Worksheets("A1")
                ComboBoxscname.List = .Range("B2:B" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value
    End With
End Sub

我用黄色突出显示了与“ B”列重复的内容,它应该仅在组合框中显示一次

我有另一种解决方案,但是在选择特定工作表名称时出现错误

Sub ComboBoxscnameList()

Dim LR As Long
Dim ctrl As Object
'Set ctrl = Sheets("A1").Select

LR = Cells(Rows.Count, "B").End(xlUp).Row

ctrl.List() = CreateArray(Range("B2:B" & LR))

End Sub

'creates an array from a given range
'ignores blanks and duplicates

Function CreateArray(r As Range)
    Dim col As New Collection, c As Range, TempArray(), i As Long

    'for each cell in range r
    For Each c In r
        On Error Resume Next
        col.Add c.Value, CStr(c.Value)
        If Err.Number = 0 And Trim(c) <> "" Then
            ReDim Preserve TempArray(i)
            TempArray(i) = c.Value
            i = i + 1
        End If
        Err.Clear
    Next

    CreateArray = TempArray
    Erase TempArray

End Function

Private Sub ComboBoxscname_DropButtonClick()
Call ComboBoxscnameList            
End Sub
excel
1个回答
0
投票

ColumnRange保存唯一值集的最简单方法是使用Dictionary。您遍历B列中的单元格,并检查Dictionary键中是否已经存在每个单元格,语法为Dict.Exists("your_parameters")

您可以阅读有关使用Dictionary HERE的更多信息。

查看下面的修改后的代码,您要将其添加到UserForm_Initialize()事件中。

修改后的代码] >>

Private Sub UserForm_Initialize()


Dim i As Long, ArrIndex As Long, LastRow As Long
Dim Dict As Object, Key As Variant
Dim HSNArr() As String

Application.ScreenUpdating = False

' us a Dictionary, and save unique Eco-System as array
Set Dict = CreateObject("Scripting.Dictionary")

With ThisWorkbook.Worksheets("Sheet2") ' <-- modify to your sheet's name
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    ReDim HSNArr(1 To LastRow) ' redim HSN array >> will optimize size later
    ArrIndex = 1

    For i = 2 To LastRow
        If Not Dict.Exists(.Range("B" & i).Value2) And Trim(.Range("B" & i).Value2) <> "" Then  ' make sure not in Dictionary and ignore empty cells
            Dict.Add .Range("B" & i).Value2, .Range("B" & i).Value2 ' add current HSN
            HSNArr(ArrIndex) = .Range("B" & i).Value2
            ArrIndex = ArrIndex + 1
        End If
    Next i
End With
ReDim Preserve HSNArr(1 To ArrIndex - 1) ' resize to populated size of Array

Application.ScreenUpdating = True

With Me.ComboBoxscname
    .Clear ' clear previous combo-box contents
    For i = 1 To UBound(HSNArr) ' loop through array, add each unique HSN to Combo-Box
        .AddItem HSNArr(i)
    Next i

    ' show default value
    .Value = HSNArr(1)
End With

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.