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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15348730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:58:23  来源:igfitidea点击:

Loop through all unbound controls on a form and clear data

vbams-accessaccess-vbams-access-2010

提问by prayingmantes

I would like to loop through all UNBOUND controls on my form and clear their data or reset their values. I have textboxes, comboboxes and checkboxes. Every time I try something like this:

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

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

I get a runtime error saying:

我收到一个运行时错误说:

438 This object doesn't support this property or method.

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

回答by HansUp

That code loops through everycontrol in the form's Controlscollection. The collection includes controls, such as labels and command buttons, which are neither bound nor unbound ... so attempting to reference their .ControlSourcegenerates that error.

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

For a control such as an unbound text box, its .ControlSourceproperty is an empty string, not Null.

对于未绑定文本框等控件,其.ControlSource属性为空字符串,而不是 Null。

So as you loop through the controls, inspect the .ControlSourcefor only those control types you wish to target. In the following example I chose text and combo boxes. When the .ControlSourceis a zero-length string, set the control's .Valueto 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