Excel VBA – 用于填充不添加重复项的ComboBox的循环

我用一个循环在一个用户窗体上填充一个ComboBox,它在表的第一列中添加所有的“名称”,在第二列中具有相同的“types”。

我不想详细说明,但同一个“名称”可能会多次出现。 我不想循环来添加这些重复值。

我在其他论坛上find了一些解决scheme,但是对于我来说这些看起来非常过时,我觉得这应该有一个简单的解决方法。 (这些“过时”的解决scheme就像30多个句子代码,我不觉得我需要这样的)

任何人都可以帮助我进一步呢?

这是填充循环:

With resourceSheet.ListObjects("Table3") For x = 2 To .ListRows.Count + 1 If .Range(x, 2) = cType Then 'cbname is the combobox cbName.AddItem .Range(x, 1) End If Next x End With 

尝试这个:

 ' Create Dictionary object Dim obj As Object Set obj = CreateObject("Scripting.Dictionary") With resourceSheet.ListObjects("Table3") For x = 2 To .ListRows.Count + 1 If .Range(x, 2) = cType Then ' If name doesn't exist in the Dictionary object yet, add the name to the listbox and the Dictionary object If IsEmpty(obj.Item(.Range(x, 1) & "")) Then 'cbname is the combobox cbName.AddItem .Range(x, 1) obj.Item(.Range(x, 1) & "") = .Range(x, 1) End If End If Next x End With 

字典对象允许您使用该名称作为关键字。 如果密钥不存在,则将该名称添加到列表框并添加该密钥。 下次碰到相同的名称,该键已经存在,所以可以移动到下一行。

这些“过时”的解决scheme就像30多个句子代码,我不觉得我需要这个

虽然你已经有了答案,但这里还有一个使用集合的选项

 Sub Sample() Dim Col As New Collection, itm As Variant With resourceSheet.ListObjects("Table3") For x = 2 To .ListRows.Count + 1 If .Range(x, 2) = cType Then On Error Resume Next Col.Add .Range(x, 2).Value, CStr(.Range(x, 2).Value) On Error GoTo 0 End If Next x End With For Each itm In Col cbName.AddItem itm Next End Sub