Search code examples
ms-accesscomboboxvbams-access-2010

Check to see if combobox values matches more than two times


I am trying to fire an event if a specific combobox value appears more than 3 times ("md") in my control set. At the moment however, I keep getting high values like 32 or 40 despite there only being 8 comboboxes on my Access form. What am I doing wrong?

Dim mdCount As Integer
For Each ctl In Me.Controls
    If ctl.ControlType = acComboBox Then
        Set cmb = ctl
        If (currentDropDown.Value = cmb.Value) And (Not currentDropDown Is cmb) And (Not currentDropDown.Value = "md") Then
            MsgBox "You cannot select the same value twice."
        End If
        If (currentDropDown.Value = "md") Then
            mdCount = mdCount + 1
        End If
    End If
Next ctl
Set ctl = Nothing

Private Sub Submit_Click()
'MsgBox mdCount
If (mdCount > 2) Then 
    MsgBox "Error!"
    Exit Sub
End Sub

Solution

  • If i understand you correctly... try something like this (bit hard-coded, but very quick):

    Function CheckMatches() As Integer
    Dim sTmp As String
    
    sTmp = IIf(Nz(Me.Combo1.Value, "") = "md", ";", "") & _
            IIf(Nz(Me.Combo2.Value, "") = "md", ";", "") & _
            IIf(Nz(Me.Combo3.Value, "") = "md", ";", "")  'and so on...
    
    CheckMatches = UBound(Split(sTmp, ";")) + 1
    '+1 is necessary in case of Option Base 0, _
    'because LBound(array) starts from 0
    
    End Function
    

    Usage:

    Private Sub Submit_Click()
    Dim mdCount as Integer
    mdCount = CheckMatches
    If (mdCount > 2) Then 
        MsgBox "Error!"
        Exit Sub
    End Sub
    

    Your requirements are not clear, so i can't help more ;(