检查并比较在组合框中输入的值

时间:2018-05-31 00:44:28

标签: excel-vba vba excel

我在Excel 2010中使用VBA。我想知道是否有一种简单的方法可以检查组合框中输入的值是否与组合框中已填充的值匹配。

Private Sub cmbMonth_Enter() With Me.cmbMonth .AddItem "January" .AddItem "February" .AddItem "March" .AddItem "April" .AddItem "May" .AddItem "June" .AddItem "July" .AddItem "August" .AddItem "September" .AddItem "October" .AddItem "November" .AddItem "December" End With End Sub

如您所见,此组合框中填充了月份名称的值。我想做的是,如果用户手动输入一个月并拼错它,退出时,检查并查看他们输入的内容是否与组合框中的内容匹配,如果没有显示消息框。

谢谢。

1 个答案:

答案 0 :(得分:0)

这样做突出显示拼写错误的条目将焦点重置为组合框:

Private Sub ComboBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Dim val As Variant
    With Me.ComboBox1 ' rename, if necessary
        val = .Value
        If .ListIndex = -1 And val <> vbNullString Then
            Cancel = True
            .SelStart = 0
            .SelLength = Len(val)
            Debug.Print "Illegal entry!" ' remove in production or replace with MsgBox
        End If
    End With
End Sub