【问题标题】:Issue with preventing duplicates in listbox防止列表框中重复的问题
【发布时间】:2019-11-08 01:16:07
【问题描述】:

我在阻止将重复项添加到 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

【问题讨论】:

  • 你循环的是列而不是行
  • 谢谢,刚刚意识到并编辑了代码。它永远不会进入循环,因为盒子的初始列表计数是 0。
  • 你必须等到你完成循环后才能添加项目,否则你只是检查第一个项目是否匹配。

标签: excel vba


【解决方案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

【讨论】:

  • 谢谢,这很完美。现在我明白了,我只看第一项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多