如何用If语句防止ComboBox值重复添加至ListBox?
解决ComboBox选中值添加至ListBox时的重复判断问题
你的核心问题是错误地直接用单个值和ListBox的整个List数组做比较,这无法正确检测重复项。需要通过循环遍历ListBox的每一项,逐一比对来判断是否已存在。
修改后的完整代码
Private Sub cmdplayer_Click() Dim ratio As Double Dim formatratio As String Dim name As String Dim isExists As Boolean Dim i As Integer Me.listbox.ColumnCount = 2 isExists = False '初始化重复标记为不存在 If cmbComboBox.Value = "" Then MsgBox "Please Select a Player" Else '获取要添加的玩家名称 name = Me.cmbComboBox.Column(0) '遍历ListBox所有项,检查是否已存在 For i = 0 To Me.listbox.ListCount - 1 If Me.listbox.List(i, 0) = name Then isExists = True Exit For '找到重复项,提前退出循环 End If Next i '根据标记判断是否添加 If isExists Then MsgBox name & " has already been added to your team" Else ratio = Me.cmbComboBox.Column(3) formatratio = FormatNumber(ratio, 1) Me.listbox.AddItem name Me.listbox.List(Me.listbox.ListCount - 1, 1) = formatratio End If End If End Sub
关键逻辑说明
- 新增
isExists布尔变量,用来标记选中的玩家是否已在ListBox中 - 通过
For i = 0 To Me.listbox.ListCount - 1遍历ListBox的每一行(ListBox的索引从0开始) - 比对ListBox第i行第0列(对应你添加的玩家名称)和ComboBox选中的名称,找到匹配项就设置
isExists = True并退出循环,避免不必要的遍历 - 最后根据
isExists的值决定是弹出提示还是执行添加操作
内容的提问来源于stack exchange,提问作者OhMyGoodness
相关产品推荐
相关产品推荐

