【问题标题】:How to loop through all controls in a form, including controls in a subform - Access 2007如何遍历表单中的所有控件,包括子表单中的控件 - Access 2007
【发布时间】:2011-03-21 15:41:58
【问题描述】:

正如我的问题的标题所暗示的,如何遍历表单中的所有控件,包括子表单。

例如我使用下面的子程序来设置带有标签*的控件的背景颜色

Public Sub colCtrlReq(frm As Form)
'  Sets background color for required field -> Tag = *
Dim setColour As String
setColour = 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 InStr(1, ctl.Tag, "*") <> 0 Then
                ctl.BackColor = setColour
            End If
        End If
Next ctl
Set ctl = Nothing
End Sub

如何改变它以捕获子表单中的控件? 在此先感谢您的帮助或指点。

干杯 诺埃尔

【问题讨论】:

  • 其他人已经回答了我们的问题,但您确实应该将其更改为:“For Each ctl In frm” -- 改为“For Each ctl In frm.Controls”。表单的默认集合实际上是 Controls 和 Fields 集合的联合,因此您编写的内容可能会产生意想不到的结果。
  • Cheers David 感谢您的建议,已更正上述代码。
  • 重新评论 "For Each ctl In frm" -- 我无法使用 Access 2010 重现此问题。

标签: vba ms-access ms-access-2007


【解决方案1】:

你可以使用递归

Public Sub colCtrlReq(frm As Form)
''  Sets background color for required field -> Tag = *
Dim setColour As String
setColour = RGB(255, 244, 164)
Dim ctl As Control
For Each ctl In frm
        If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox _
            Or ctl.ControlType = acListBox Then
            If InStr(1, ctl.Tag, "*") <> 0 Then
                ctl.BackColor = setColour
            End If
        ElseIf ctl.ControlType = acSubform Then
            colCtrlReq frm(ctl.Name).Form

        End If
Next ctl
Set ctl = Nothing
End Sub

【讨论】:

  • 不错的 Remou,看起来和我所追求的技术一模一样。
  • @Remou 做this achieve its purpose? :-)
  • 很好的答案。我注意到您可以将 frm(ctl.Name).Form 简化为 ctl.Form(已在 Access 2016 中验证)。
  • 但是如何调用这个程序呢?在加载事件或其他任何事情上使用表单?使用 on click 或 so 事件为每个控件调用此过程非常费力!
【解决方案2】:

访问子窗体控件的 Form 属性的控件集合。

请注意,子表单控件的名称可能与保存的表单对象的名称不同。

如果你的子表单控件被命名为SubformControlName,从这里开始:

For Each ctl In frm!SubformControlName.Form.Controls
    Debug.Print ctl.Name
Next

更新:根据您的评论,我认为您正在寻找以下内容。

如果您事先不知道子表单控件的名称,您可以在运行时识别表单的哪些控件是子表单控件。

For Each ctl In frm.Controls
    If TypeName(ctl) = "SubForm" Then
        Debug.Print ctl.Name & " is a SubForm"
        For Each ctlSub in ctl.Form.Controls
            Debug.Print ctlSub.Name
        Next 
    End If
Next

【讨论】:

  • 干杯 HAnsUp。如果您没有表单中子表单的名称(可能是名称),那么您如何遍历控件呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-24
  • 2016-10-30
相关资源
最近更新 更多