如何避免列表框中的重复值

时间:2012-07-16 04:51:40

标签: vb6

表1

ID Division Dept

001 CS IT
002 CD Admin
003 AS Admin

我想在列表框中加载没有重复值的部门

尝试代码

Dim rdoRs As New ADODB.Recordset
Dim record As Variant
Dim Div As Variant
Dim usr, MySQL As String
usr = "CD,AS,"
record = Split(usr, ",")
For Each Div In record
MySQL = "Select Distinct dept from table1 Where division = '" & div & "'"
   rdoRs.Open MySQL, conn1
   If rdoRs.RecordCount > 0 Then
      Do While Not rdoRs.EOF
         listbox1.AddItem rdoRs!dept
           rdoRs.MoveNext
           Loop
   End If
   rdoRs.Close
Next

输出

Listbox1

Admin 'Loaded for CD Division
Admin 'Loaded for AS Division

上面的代码工作正常,但它正在加载2次管理部门。在列表框中。因为For Loop正在加载CD的部门管理员,并且它再次加载了部门的部门管理员。

我不想在列表框中显示重复的值。

预期产出

Listbox1

Admin  'Loaded for both CD and AS Division

如何在VB6中执行此操作。

需要VB6代码帮助。

2 个答案:

答案 0 :(得分:1)

编写一个函数来检查它是否已经在列表中......

Public Function FindInList(theList as ListBox, theString as String)
    Dim i as Integer
    theString = LCase(Trim(theString))

    For i = 0 to theList.ListCount - 1
        If LCase(Trim(theList.List(i))) = theString then
            FindInList = i
            Exit Function
        End If
    Next i

    FindInList = -1
End Function

然后,当您想要将内容添加到列表中时,只需执行...

If FindInList(List1, StringToAdd) = -1 Then List1.AddItem(StringToAdd)

答案 1 :(得分:0)

您可以在查询中执行此操作

更改

MySQL = "Select dept from table1 Where division = '" & div & "'" 

类似

MySQL = "Select DISTINCT dept from table1 Where division = '" & div & "'"