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