我有两个ListBoxes。 ListBox1具有可由用户通过双击项目或按添加按钮传输到ListBox2的项目列表。我现在要做的是阻止用户在ListBox2中添加重复项。如果检测到重复,则消息将提示“已包含项目”并结束代码。我猜这可以用contains来完成吗?但我不知道该怎么做。我有以下代码:
'Report Listing
Private Sub UserForm_Initialize()
'List of Reports
With ListBox1
.AddItem "Report 1"
.AddItem "Report 2"
.AddItem "Report 3"
.AddItem "Report 4"
.AddItem "Report 5"
.AddItem "Report 6"
End With
End Sub
'Add selection to ListBox2
Private Sub AddButton_Click()
With ListBox1
Dim itemIndex As Integer
For itemIndex = .ListCount - 1 To 0 Step -1
If .Selected(itemIndex) Then
ListBox2.AddItem .List(itemIndex)
End If
Next itemIndex
End With
End Sub
'Double click to Add
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
ListBox2.AddItem ListBox1.List(ListBox1.ListIndex)
End Sub
答案 0 :(得分:1)
这样的事情有望帮助你......
AddValueListbox2
函数检查是否存在值,如果不存在则添加它,如果存在,则向用户发出警报。
<强> NB 强> 如果为列表框启用了多选,则将。
Private Sub CommandButton1_Click()
'index is -1 if nothin is selected
If ListBox1.ListIndex = -1 Then Exit Sub
'loop backwards as we're removing items
For i = ListBox1.ListCount - 1 To 0 Step -1
If ListBox1.Selected(i) Then
AddValueListbox2 ListBox1.List(i)
ListBox1.RemoveItem (i)
End If
Next i
End Sub
Private Function AddValueListbox2(str As String)
Dim valExists As Boolean
valExists = False
For i = 0 To ListBox2.ListCount - 1
If ListBox2.List(i) = str Then valExists = True
Next i
If valExists Then
MsgBox str & " has already been added to ListBox", vbInformation
Else
ListBox2.AddItem str
End If
End Function
Private Sub UserForm_Activate()
Dim items(2) As String
items(0) = "foo"
items(1) = "bar"
items(2) = "baz"
For i = LBound(items) To UBound(items)
Me.ListBox1.AddItem items(i)
Next i
End Sub
答案 1 :(得分:1)
如果有人仍然感兴趣,还有另一种方法可以使用类似的技术。
Sub Duplicate()
dim i as integer
dim x as integer
x = 0
For i = 0 to listbox2.count - 1
If listbox2.list(i) = myval Then
x = x + 1
End If
Next i
If x = 0 Then
listbox2.additem myval
End If
End Sub
其中myval是listbox1中的选定值。
基本上,如果它在列表中找到对您的值的单个引用,它将启动一个计数器。如果找不到您的值的实例,它会将其插入列表框。
希望这有助于某人。