从Excel组合框中删除重复项

时间:2018-06-12 15:52:19

标签: excel vba combobox populate

我目前在Excel中的UserForm上有几个组合框,可以从条目自动填充到工作簿中的特定列。但是,这些组合框会自动填充重复项,我不希望这样。我应该如何调整我的代码以仅填充唯一值?感谢。

以下是我的组合框代码:

   Private Sub UserForm_Initialize()
    With Worksheets("Sheet1")
        txtContractVehicle.List = .Range("E2:E" & .Range("E" & .Rows.Count).End(xlUp).Row).Value
        txtCapability.List = .Range("F2:F" & .Range("F" & .Rows.Count).End(xlUp).Row).Value
        txtAgency.List = .Range("G2:G" & .Range("G" & .Rows.Count).End(xlUp).Row).Value
        txtDepartment.List = .Range("H2:H" & .Range("H" & .Rows.Count).End(xlUp).Row).Value
        txtSocioeconomic.List = .Range("I2:I" & .Range("I" & .Rows.Count).End(xlUp).Row).Value
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

你可以使用一个辅助函数来“过滤”一些传递的数组并仅为了利用Dictionary对象的实例而保留唯一值

Function RemoveDuplicates(vals As Variant) As Variant
    Dim val As Variant
    With CreateObject("Scripting.Dictionary")
        For Each val In vals
            .Item(val) = 1
        Next
        RemoveDuplicates = .Keys
    End With
End Function

Private Sub UserForm_Initialize()
    With Worksheets("Sheet1")
        txtContractVehicle.list = RemoveDuplicates(.Range("E2:E" & .Range("E" & .Rows.Count).End(xlUp).row).Value)
        ...
    End With
End Sub