2017-09-13 43 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'就可以做到。查看更新的答案。 –