VBA 窗体一键清空所有控件内容的代码
要一键清空 VBA 窗体中所有控件的内容,可以使用以下代码:
Private Sub CommandButton1_Click()
Dim ctl As Control
For Each ctl In Me.Controls
If TypeOf ctl Is TextBox Or TypeOf ctl Is ComboBox Or TypeOf ctl Is ListBox Then
ctl.Value = ""
ElseIf TypeOf ctl Is CheckBox Or TypeOf ctl Is OptionButton Then
ctl.Value = False
ElseIf TypeOf ctl Is OptionGroup Then
Dim opt As Control
For Each opt In ctl.Controls
If TypeOf opt Is OptionButton Then
opt.Value = False
End If
Next opt
End If
Next ctl
End Sub
在上面的代码中,假设你将清空按钮命名为 'CommandButton1'。当点击清空按钮时,会触发 'CommandButton1_Click' 事件。通过使用 'For Each' 循环遍历窗体中的每个控件,并根据控件类型执行清空操作。
对于文本框 ('TextBox')、下拉框 ('ComboBox')、列表框 ('ListBox'),可以通过将控件的 'Value' 属性设置为空字符串来清空其内容。
对于复选框 ('CheckBox') 和单选按钮 ('OptionButton'),可以通过将 'Value' 属性设置为 'False' 来取消选择。
对于选项组 ('OptionGroup'),需要进一步遍历选项组中的每个控件,并将其 'Value' 属性设置为 'False'。需要注意的是,选项组中的其他控件如果不是单选按钮,可能会触发错误,因此在代码中进行了类型检查。
注意,这段代码应该写在窗体的 'Code Module' 中,而不是普通的模块中。
原文地址: https://www.cveoy.top/t/topic/1P4 著作权归作者所有。请勿转载和采集!