只有Combobox(VBA)中的唯一记录

时间:2011-10-20 18:21:04

标签: excel vba

我有一个组合框,我在Excel工作表中添加了一些东西。我只想要唯一的记录,我希望在切换到此页面时更新它们。 为此,我使用了以下代码:

Private Sub MultiPage1_Change()
Dim Rand As Long
Dim ws As Worksheet
Set ws = Worksheets("BD_IR")
Dim i As Long
Rand = 3
Do While ws.Cells(Rand, 3).Value <> "" And Rand < 65536
    If Me.repereche.ListCount <> 0 Then
        For i = 0 To (Me.repereche.ListCount)
        If Me.repereche.List(i, 0) <> Mid(ws.Cells(Rand, 3).Value, 4, 10) Then
            Me.Controls("repereche").AddItem Mid(ws.Cells(Rand, 3).Value, 4, 10)
        End If
        Next i
    ElseIf Me.repereche.ListCount = 0 Then
        Me.Controls("repereche").AddItem Mid(ws.Cells(Rand, 3).Value, 4, 10)
    End If
    Rand = Rand + 1
Loop

这段代码的问题(我不知道问题出在哪里?)是每当我更改页面并回到这个组合框所在的页面时......它会增加更多(不是唯一的)和更多物品。我哪里错了?

1 个答案:

答案 0 :(得分:8)

试试这段代码:

Dim ws As Worksheet
Dim rCell As Range

Set ws = Worksheets("BD_IR")

'//Clear combobox
repereche.Clear

With CreateObject("Scripting.Dictionary")
    For Each rCell In ws.Range("C3", ws.Cells(Rows.Count, "C").End(xlUp))
        If Not .exists(rCell.Value) Then
            .Add rCell.Value, Nothing
        End If
    Next rCell

    repereche.List = .keys
End With

我更倾向于集合,因为您可以检查字典中是否存在值而不是使用错误并立即将整个集合添加到组合框中。