2012-07-16 74 views
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 

上面的代碼是w奧可福罰款,但它是加載2倍管理部門。在列表框中。由於For Loop正在加載CD的部門管理員,並且它正在加載AS部門的部門管理員。

我不想在列表框中顯示重複的值。

預期輸出

Listbox1 

Admin 'Loaded for both CD and AS Division 

如何在VB6做到這一點。

需要VB6代碼幫助。

回答

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) 
+0

,它不應該提供重複值對不起,代碼中有一個錯誤,它將LCase()的d字符串與未知情況的字符串進行比較。這會導致代碼無法工作。現在修復。 – TimFoolery 2012-07-16 05:30:46

0

您可以在查詢做到這一點

變化

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

喜歡的東西

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

下站在我的問題,請,我不SQL查詢有問題,我也知道不同的值,FOR循環重複給予值... – JetJack 2012-07-16 05:00:35

+0

如果您正在使用DISTINCT – 2012-07-16 05:18:47