Excel VBA 将项目添加到组合框而没有重复项目

jav*_*vad 3 excel vba

我想将下面的项目添加到组合框,但如果有一个项目的重复项,那么应该只添加一个。

   A
1 john  
2 john
3 marry
4 marry
5 john
6 lisa
7 frank
8 marry
Run Code Online (Sandbox Code Playgroud)

我想组合框的结果是johnmarrylisafrank(而不是八个项目四个独特的项目)。


我的代码是:

Private Sub Workbook_Open()

    Application.EnableEvents = False

    With Sheet2.ComboBox1

        For Each Cell In Sheet1.Range("A1:A6348")
            If Not ComboBox1.exists(Cell.Value) Then
                .AddItem  Cell.Value
            End If
        Next

    End With

End Sub
Run Code Online (Sandbox Code Playgroud)

use*_*813 5

添加唯一项的另一种方法是使用Dictionary对象。

见下文:

Dim rngItems As Range
Dim oDictionary As Object

Set rngItems = Range("A1:A8")
Set oDictionary = CreateObject("Scripting.Dictionary")

With Sheet1.ComboBox21
    For Each cel In rngItems
        If oDictionary.exists(cel.Value) Then
            'Do Nothing
        Else
            oDictionary.Add cel.Value, 0
            .AddItem cel.Value
        End If
    Next cel
End With
Run Code Online (Sandbox Code Playgroud)