1

表格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 加载部门管理员,并且再次为 AS 部门加载部门管理员。

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

预期产出

Listbox1

Admin  'Loaded for both CD and AS Division

如何在 VB6 中做到这一点。

需要 VB6 代码帮助。

4

2 回答 2

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)
于 2012-07-16T05:22:53.707 回答
0

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

改变

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

类似于

MySQL = "Select DISTINCT dept from table1 Where division = '" & div & "'" 
于 2012-07-16T04:55:09.577 回答