遍历表单上的所有未绑定控件并清除数据

pra*_*tes 3 ms-access vba access-vba ms-access-2010

我想循环遍历表单上的所有UNBOUND控件并清除其数据或重置其值.我有文本框,组合框和复选框.每次我尝试这样的事情:

Dim ctl As Control
    For Each ctl In Me.Controls
        If IsNull(ctl.ControlSource) Then
            ctl.Value = Nothing
        End If
    Next ctl
Run Code Online (Sandbox Code Playgroud)

我收到运行时错误说:

438此对象不支持此属性或方法.

Han*_*sUp 12

该代码循环遍历表单集合中的每个控件Controls.该集合包括控件,如标签和命令按钮,既不绑定也不绑定...因此尝试引用它们会.ControlSource生成该错误.

对于诸如未绑定文本框之类的控件,其.ControlSource属性为空字符串,而不是Null.

因此,当您遍历控件时,.ControlSource仅检查您希望定位的控件类型.在以下示例中,我选择了文本和组合框.当.ControlSource为零长度字符串时,将控件设置.Value为Null.

For Each ctl In Me.Controls
    Select Case ctl.ControlType
    Case acTextBox, acComboBox ' adjust to taste
        'Debug.Print ctl.Name, Len(ctl.ControlSource)
        If Len(ctl.ControlSource) = 0 Then
            ctl.value = Null
        End If
    Case Else
        ' pass
    End Select
Next
Run Code Online (Sandbox Code Playgroud)