Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Listbox - Item Already Exists?

Status
Not open for further replies.
Aug 17, 2008
28
How do I check if a piece of text already exists in a listbox and, if needed, prevent it being added again?

I checked Google, but once again it proved useless.
 
Dim i As Integer, j As Integer
Dim ProposedEntry As String
Dim ArrayOfDays As Variant

ArrayOfDays = Array("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")

For i = 1 To 100
ProposedEntry = ArrayOfDays(CInt(Rnd * 6))
For j = 0 To List1.ListCount - 1
If List1.List(j) = ProposedEntry Then Exit For
Next
If j = List1.ListCount Then List1.AddItem ProposedEntry
Next
 
Or...

Option Explicit

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const LB_FINDSTRING As Long = &H18F

Private Sub Command2_Click()

Dim i As Integer
Dim ProposedEntry As String
Dim ArrayOfDays As Variant

ArrayOfDays = Array("Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun")

For i = 1 To 100
ProposedEntry = ArrayOfDays(CInt(Rnd * 6))
If SendMessage(List1.hWnd, LB_FINDSTRING, -1, ByVal ProposedEntry) < 0 Then List1.AddItem ProposedEntry
Next

End Sub
 

How about:
Code:
Private Sub Command1_Click()
Dim i As Integer
Dim blnItemIsThere As Boolean

For i = 0 To List1.ListCount - 1
    If Trim$(UCase(List1.List(i))) = Trim$(UCase(Text1.Text)) Then
        blnItemIsThere = True
        Exit For
    End If
Next i

If Not (blnItemIsThere) Then
    List1.AddItem Text1.Text
Else
    MsgBox Text1.Text & " Already in ListBox"
End If

End Sub
If you use TextBox1 as a way to add items to List1 listbox.

Have fun.

---- Andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top