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
Loop through all unbound controls on a form and clear data
提问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 Controls
collection. The collection includes controls, such as labels and command buttons, which are neither bound nor unbound ... so attempting to reference their .ControlSource
generates that error.
该代码循环遍历表单集合中的每个控件Controls
。该集合包括控件,例如标签和命令按钮,它们既没有绑定也没有绑定……因此尝试引用它们会.ControlSource
产生该错误。
For a control such as an unbound text box, its .ControlSource
property is an empty string, not Null.
对于未绑定文本框等控件,其.ControlSource
属性为空字符串,而不是 Null。
So as you loop through the controls, inspect the .ControlSource
for only those control types you wish to target. In the following example I chose text and combo boxes. When the .ControlSource
is a zero-length string, set the control's .Value
to 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