我正在构建一个包含两个ListBox的Userform,以便用户可以从ListBox1中选择选项并将它们添加到ListBox2,或者从ListBox2中删除选项
我正在努力的是如何防止将重复项添加到ListBox2?本质上,我想构建一个函数(?),它检查ListBox2中是否已包含一个选项
Private Sub CommandButton3_Click()
'### Adds Items from ListBox1 to ListBox2
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then ListBox2.AddItem ListBox1.List(i)
Next i
ListBox1.Selected
End Sub
Private Sub CommandButton4_Click()
'### Removes Items from ListBox2
Dim counter As Integer
counter = 0
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i - counter) Then
ListBox2.RemoveItem (i - counter)
counter = counter + 1
End If
Next i
End Sub
答案 0 :(得分:1)
以下代码可以解决问题:
Private Sub CommandButton3_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then
valCheck (ListBox1.List(i))
End If
Next i
End Sub
Private Function valCheck(str As String)
'### Adds Items from ListBox1 to ListBox2
Dim valExists As Boolean
valExists = False
For i = 0 To ListBox2.ListCount - 1
If ListBox2.List(i) = str Then
valExists = True
End If
Next i
If valExists Then
MsgBox ("already exists")
Else
ListBox2.AddItem str
End If
End Function
Private Sub CommandButton4_Click()
'### Removes Items from ListBox2
For i = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(i) = True Then ListBox2.RemoveItem (i)
Next i
End Sub