vba - 遍历特定的表单控件

vba - looping over specific form controls

我有一个包含 5 个下拉框的访问表单,我需要在批准表单之前检查下拉框的值是否唯一。我可以遍历所有表单元素,但我希望只能遍历下拉列表:

----------------------------------------------------------------------
|Id1 [dropdown values] Id2 [Dropdown values]  Id3 [Dropdown Values]   |
|                                                                     |  
|  CollectionTask [Another dropdown]                                  |    
|  []This is a checkbox                                               |
|               [Approve Button] [clear myForm btn]                   |
----------------------------------------------------------------------

'iterating over the form elements 
 On Error Resume Next
    Dim ctl As Control
    For Each ctl In Me.Controls
        'do something only for dropdown controls of form
    Next

我不想遍历所有内容,而是只想遍历下拉列表类型。我觉得应该有办法做到这一点。我正在使用下面的技术解决这个问题,但这需要很多代码。

'this code will do the trick but that means I will have to write a condition for every id
'which for me is lots of code (not being lazy but I think iterating over the form elements will be more efficient 
If (id1.Value = id2.Value) Or (id1.Value = id3.Value) Or (id1.Value = id4.Value) then
       Msgbox "make sure you are not duplicating ids"

End if

使用以下代码,您可以检查所有带有 ControlTypeacComboBox 的控件。基本上它只是将 ComboBox 的值添加到 Dictonary 中,每次检查该值是否已存在于 Dictonary 中。如果该值已在另一个 ComboBox 中设置,您只需要确定要发生什么。

这是徒手编写的代码,但我相当确定一切都是正确的:

 Private Sub CheckCombos()
     Dim ctl As Control
     Dim dict As Variant

     Set dict = CreateObject("Scripting.Dictionary")


     For Each ctl In Me.Controls

         If ctl.ControlType = acComboBox Then 

             If Nz(ctl.Value,"") <> "" Then 

                 If dict.Exists(ctl.Value) Then 
                    Msgbox "Combobox: " & ctl.Name & " has the same value as: " & dict(ctl.Value)
                 Else 
                    dict.Add ctl.Value, ctl.Name
                 End If

             Else 
                 Msgbox "Empty Combobox" 
                 'Handle exit
             End If 

         End If
     Next
  End Sub