vba - 循环特定的表单控件

时间:2015-06-23 14:50:38

标签: vba ms-access access-vba ms-access-2003

我有一个包含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

1 个答案:

答案 0 :(得分:1)

使用以下代码,您可以使用ControlType acComboBox检查所有控件。基本上,每次只需将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