防止在列表框中重复的问题

时间:2019-11-07 15:56:16

标签: excel vba

我遇到了一些问题,无法将重复项添加到Excel中的列表框中。我有两个列表框,lstBoxSurveyList和lstBoxSurveyRemove。我正在尝试从lstBoxSurveyList添加项目,但前提是它不在lstBoxSurveyRemove中。我的代码在下面(只需对其进行编辑)。有什么建议么?我在VB.Net上看到了一些帖子,但是它们似乎在Excel中不起作用。

    Dim i As Integer

    For i = 0 To lstBoxSurveyRemove.ListCount - 1
        If lstBoxSurveyRemove.List(i) = lstBoxSurveyList.Value Then
            MsgBox ("This value exists")
        Else
            lstBoxSurveyRemove.AddItem (lstBoxSurveyList.Value)
        End If

    Next i

1 个答案:

答案 0 :(得分:1)

您必须等到循环完成后才能添加项目,否则,您只是在检查第一个项目是否匹配。

类似这样的东西:

Dim i As Long, bFound As Boolean

For i = 0 To lstBoxSurveyRemove.ListCount - 1
    If lstBoxSurveyRemove.List(i) = lstBoxSurveyList.Value Then
        bFound = True
        Exit For
    End If
Next i
If Not bFound Then lstBoxSurveyRemove.AddItem lstBoxSurveyList.Value