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

时间:2015-02-19 15:06:31

标签: excel-vba vba excel

我想将以下项目添加到组合框中,但如果项目有重复项,则只应添加一项。

   A
1 john  
2 john
3 marry
4 marry
5 john
6 lisa
7 frank
8 marry

我希望组合框结果为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

2 个答案:

答案 0 :(得分:4)

添加唯一项的另一种方法是使用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

答案 1 :(得分:3)

Get Unique Items

Sub UsingCount()
    Dim ws As Worksheet
    Dim Rws As Long, Rng As Range, c As Range, y As Integer, x

    Set ws = Sheets("Sheet1")
    Sheets("Sheet3").ComboBox1.Clear

    With ws

        Rws = .Cells(Rows.Count, "A").End(xlUp).Row

        For y = 1 To Rws

            Set c = .Cells(y, 1)
            Set Rng = .Range(.Cells(2, 1), .Cells(y, 1))

            x = Application.WorksheetFunction.CountIf(Rng, c)

            If x = 1 Then Sheets("Sheet3").ComboBox1.AddItem c
        Next y

    End With

End Sub