2017-09-13 28 views
0

我想有2个列表框,1与一堆值和一个与另一堆值,我想将它们添加到第三个列表框,然后删除所有的匹配值,2 Listboxes into 1,然后删除匹配值VBA

这里是我的代码,我走到这一步,

For i = 0 To (ListBox1.ListCount - 1) 
ListBox3.AddItem (ListBox1.List(i)) 
Next 

Dim qstring As String 


For i = 0 To (ListBox2.ListCount - 1) 

qstring = ListBox1.List(i) 

With Me.ListBox3 
     'Loop through combobox 
     For b = 0 To .ListCount - 1 
      If .List(b) = qstring Then 
       strFound = True 
       Exit For 
      End If 
     Next b 
     'Check if we should add item 
     If Not strFound Then .AddItem (qstring) 
    End With 

Next 

修订,感谢你的帮助,先生,我现在想知道为什么我收到此错误,谢谢!

Error

+0

什么不工作/有什么错误? –

回答

0

您可以使用对象的Scripting.Dictionary允许的唯一密钥。您可以使用.Exists方法检查项目是否存在。

Sub Whatever() 
    Dim obj As Object 
    Set obj = CreateObject("Scripting.Dictionary") 

    '1st ListBox 
    For i = 0 To ListBox1.ListCount - 1 
     If Not obj.Exists(CStr(ListBox1.List(i))) Then 
      obj.Add CStr(ListBox1.List(i)), vbNullString 
     End If 
    Next 

    '2nd ListBox 
    For i = 0 To ListBox2.ListCount - 1 
     If Not obj.Exists(CStr(ListBox2.List(i))) Then 
      obj.Add ListBox2.List(i), vbNullString 
     End If 
    Next 

    'add unique list to 3rd ListBox 
    Dim Key As Variant 
    For Each Key In obj.Keys 
     ListBox3.AddItem Key 
    Next Key 
End Sub 

编辑:

感谢@Nathan_Sav指出这一点。不需要循环来填充第三个ListBox。

​​
+0

感谢您的帮助,请参阅最新图片,但我可以看到,这正是我需要做的! –

+1

你可以跳过最后一个循环,只要说'listbox3.list = obj.keys()' –

+0

@Ashley Davies的确,我们用字典填充字典但没有值。一个简单的'vbNullString'就可以做到。查看更新的答案。 –

相关问题