如何遍历表单中的所有控件,包括子窗体中的控件 - Access 2013

时间:2016-06-07 16:10:54

标签: vba access-vba

我在这个网站上找到了这个代码,并且通过描述,它正是我需要的(加上我需要将它扩展到子表单),但我无法让它工作。我在Form的VBA区域和单独的模块中尝试过它。我也改变了作为表格' fmr作为Form_Submissions' frm。指定哪种形式。

我有一个命令按钮,其中包含点击事件代码' Application.Run" colCtrlReq"'和colCtrlReq代码保存在模块中。 ' frm As Form'防止代码被识别/找到所以我得到错误449 /参数不是可选的。

我尝试删除选项比较数据库'但是不。我尝试删除“frm As Form'从子名称中添加“Dim frm As Form'到代码但然后得到其他错误。 (我是Access的新手,所以抓住稻草。)

其他错误:
-on acTextBox.Value我得到acTextBox的编译错误/无效限定符
-on对于每个ctl在frm.Controls中我得到运行时错误91 /对象变量或变量未设置(可能因为我删除了' frm As Form'来自名称)

我的目标是:
- 如果是文本框或组合框,则必填和空白=更改背景颜色
- 如果是复选框或选项按钮,则必填,false =更改背景颜色

任何有助于此工作并将其扩展为子表单的帮助将非常感谢!

选项比较数据库

Public Sub colCtrlReq(frm As Form)
'  Sets background color for required field -> Tag = *
Dim setColor As String
setColor = RGB(255, 244, 164)
Dim ctl As Control

For Each ctl In frm.Controls
        'If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox Or ctl.ControlType = acListBox Then
        If ctl.ControlType = acTextBox And acTextBox.Value = "" And InStr(1, ctl.Tag, "*") <> 0 Then
            ctl.BackColor = setColor
        End If
Next ctl
Set ctl = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

Sub Validate()

Dim ctrl As Control
Dim l As Control

setColor = RGB(255, 0, 0)

foundrequired = 0

For Each ctrl In Form_Submissions.Controls

    If InStr(1, ctrl.Tag, "*") <> 0 Then

        If ctrl.ControlType = acTextBox Or ctrl.ControlType = acComboBox Then
            If Nz(ctrl.Value, vbNullString) = "" Then
            ctrl.BackColor = setColor
            foundrequired = foundrequired + 1
            Else
            ctrl.BackColor = 16777215
            End If
        End If

        If ctrl.ControlType = acCheckBox Or ctrl.ControlType = acOptionButton Then
            If Nz(ctrl.Value) = 0 Then
                For Each l In Form_Submissions.Controls
                    If l.ControlType = acLabel And Right(l.Name, 3) = Right(ctrl.Name, 3) Then
                    l.BackColor = setColor
                    foundrequired = foundrequired + 1
                    End If
                Next l
            Else
                For Each l In Form_Submissions.Controls
                    If l.ControlType = acLabel And Right(l.Name, 3) = Right(ctrl.Name, 3) Then
                    l.BackColor = 16777215
                    End If
                Next l
            End If
        End If

    End If

Next ctrl

If foundrequired > 0 Then
MsgBox "Please fill in the required fields before submitting.", vbCritical, "HOTEL CHECKS"
Exit Sub
End If

'continue code if passes validation

End Sub