2013-10-11 107 views
5

如何检查cmbTypeYacht.text的数据是否已经存在于cmbTypeYacht.list如何检查数据是否已存在于组合框列表中?

下面是我得到了什么:

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 

遗憾的标签我不是很确定这就是它,但即时通讯使用Microsoft Visual Basic应用程序。

+0

嗯,这是它,VB.NET或VBScript?还是VBA?我将假设VB.NET,但你没有括号...... – Ryan

回答

9

ComboBox类有一个FindStringExact()方法就可以了你,就像这样:

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 

UPDATE:

用户也可以直接通过列表循环,以及像这样:

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

谢谢karl, 我只是好奇,如果除了使用类FindStringExact()之外还有其他方法吗? – blackmaler

+0

通过列表循环? – sam092

+0

@ user2869223 - 在我的回答中查看'UPDATE:'。 –

0

您不需要遍历combobox.items。 Items.Contains已经遍历整个列表。

只需使用:

If cmbTypeYacht.Items.Contains(cmbTypeYacht.Text) Then 
    MessageBox.Show("Found It") 
    Exit For 
End If 
0

搜索:VBA检查数据是否已经存在于框列表?
但vba不具备上述属性。

Sub TestString() 
    Dim myString As String 
    Dim i As Long 
    Dim strFound As Boolean 


    'Just for test purposes 
    myString = "Apple" 


    strFound = False 
    With Me.ComboBox1 
     'Loop through combobox 
     For i = 0 To .ListCount - 1 
      If .List(i) = myString Then 
       strFound = True 
       Exit For 
      End If 
     Next i 
     'Check if we should add item 
     If Not strFound Then .AddItem (myString) 
    End With 
End Sub 

这是很多在http://www.ozgrid.com/forum/showthread.php?t=187763 搜索后发现,实际工作

0

我在Excel 2013工作并没有FindStringExact或.Items.Contains所以这两种方法都不是有效的。也不需要迭代列表。其实很简单。由于用户窗体“MyUserForm”和组合框“MyComboBox”,

Dim my_index As Integer 
my_index = -1 
my_index = MyUserForm.MyComboBox.ListIndex 
If my_index >= 0 Then 
    MsgBox "Item is in the list" 
Else 
    MsgBox "Item is NOT in the list" 
End If 

说明:设置索引的值的ListIndex不会返回(如-1)。然后尝试获取ListIndex。如果当前.Value不在列表中,则不会为my_index指定新值,它将保持-1。

相关问题