Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether the data already exists in combobox list?

Tags:

vba

How can I check if the data from cmbTypeYacht.text already exists in cmbTypeYacht.list?

Here's what I've got:

Dim TypeYacht As String 'Type of yacht input

TypeYacht = cmbTypeYacht.Text

If TypeYacht = ("cmbTypeYacht list") Then
    MsgBox "Type of Yacht is already on the list", vbExclamation, "Yacht Chantering"
Else
    cmbTypeYacht.AddItem cmbTypeYacht.Text

    With cmbTypeYacht
        .Text = ""
        .SetFocus
    End With
End If

sorry about the tag im not quite sure which is it but im using Microsoft Visual Basic app.

like image 718
blackmaler Avatar asked Oct 11 '13 00:10

blackmaler


3 Answers

The ComboBox class has a FindStringExact() method that will do the trick for you, like this:

Dim resultIndex As Integer = -1

resultIndex = cmbTypeYacht.FindStringExact(cmbTypeYacht.Text)

If resultIndex > -1 Then
    ' Found text, do something here
    MessageBox.Show("Found It")
Else
    ' Did not find text, do something here
    MessageBox.Show("Did Not Find It")
End If

You can also just loop through the list as well, like this:

Dim i As Integer = 0
For i = 0 To cmbTypeYacht.Items.Count - 1
    If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then
        MessageBox.Show("Found It")
        Exit For
    End If
Next
like image 104
Karl Anderson Avatar answered Nov 15 '22 08:11

Karl Anderson


I'm working in Excel 2013 and there is no FindStringExact or .Items.Contains so, neither of those are valid. There is also no need to iterate the list. It is very simple actually. Given a userform "MyUserForm" and a combobox "MyComboBox",

If MyUserForm.MyComboBox.ListIndex >= 0 Then
    MsgBox "Item is in the list"
Else
    MsgBox "Item is NOT in the list"
End If

Explanation: If selected item is not in the list, .ListIndex returns -1.

like image 20
SM177Y Avatar answered Nov 15 '22 09:11

SM177Y


The combobox in vba has a property called MatchFound. It will return true if the value you inputted in the combobox (ComboBox.Value) existed before.

Put below code in the update event of the combobox for trial

Private Sub ComboBox_AfterUpdate()
If ComboBox.MatchFound = True then
    Msgbox "Value exist"
End If
End Sub

Check it out: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/combobox-matchfound-property-outlook-forms-script

like image 45
Chuan Ng Avatar answered Nov 15 '22 07:11

Chuan Ng