2014-10-28 107 views
3

我用循环在用户窗体上填充组合框,它在表格的第一列中添加所有“名称”,它们具有相同的“类型”在第二列。Excel VBA - 用于填充不添加重复项的组合框的循环

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

我在其他论坛上发现了一些解决方案,但那些对我来说看起来非常过时,我觉得这应该有一个简单的修复。 (这些“过时”的解决方案就像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 
+0

您有什么机会可以告诉我们您已经找到的过时解决方案是什么?我不想提出你已经解雇的建议。 – Dave 2014-10-28 09:01:34

+0

我明白了,我所说的解决方案是30+句子代码,对我来说效率很低,所以如果你有一个更短的解决方案,我很乐意看到它 – 2014-10-28 09:14:53

回答

3

试试这个:

' 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 

Dictionary对象允许您使用的名称作为重点。如果密钥不存在,它将名称添加到列表框并添加密钥。下次遇到相同名称时,该密钥已存在,因此可以移至下一行。

+0

+1完美的作品,非常感谢! – 2014-10-28 09:31:16

+0

+ 1很好:) – 2014-10-28 11:32:57

3

这些“过时”的解决方案是像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 
另一种选择
+0

+1谢谢,这段代码对我来说更有意义@Dave的回答。没有想到这样 – 2014-10-28 11:58:08