我想要2个列表框,1个带有一堆值,1个带有另一组值,我想将它们添加到第3个列表框然后删除所有匹配的值,
这是我到目前为止的代码,
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
修改,谢谢你的帮助先生,我现在想知道为什么我收到这个错误,谢谢!
答案 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指出这一点。无需循环填充第3个ListBox。
ListBox3.List = obj.Keys()