excel vba 检查命令按钮和复选框是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24471316/
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
excel vba check if command button and checkbox exists
提问by Divin3
I have a script that uses checkboxes and command buttons, and there is a macro that resets them to default on every sheet.
我有一个使用复选框和命令按钮的脚本,并且有一个宏可以将它们重置为每个工作表上的默认值。
'opt button reset
For i = 1 To Worksheets.Count
Sheets(i).Shapes("Option Button 1").ControlFormat.Value = xlOn
Next i
'cb reset
For i = 1 To Worksheets.Count
Sheets(i).Shapes("CheckBox1").ControlFormat.Value = xlOff
Next i
The problem is that, if there is a sheet that has no checkbox or opt button, the script does not work
问题是,如果工作表没有复选框或选择按钮,则脚本不起作用
What I want to do is to check if the cb and ob exists and execute the script only than.
我想要做的是检查 cb 和 ob 是否存在并仅执行脚本。
Thanks in advance
提前致谢
回答by Portland Runner
You have a couple of options.
你有几个选择。
Quickest way: On Error Resume Next
On Error Resume Next For i = 1 To Worksheets.Count Sheets(i).Shapes("Option Button 1").ControlFormat.Value = xlOn 'opt button reset Sheets(i).Shapes("CheckBox1").ControlFormat.Value = xlOff 'cb reset Next i
Loop through objects and match name
For i = 1 To Worksheets.Count For Each myControl In Sheets(i).Shapes If myControl.Name = "CheckBox1" Then myControl.Value = xlOff ElseIf myControl.Name = "Option Button 1" Then myControl.Value = xlOn End If Next myControl Next i
最快的方法:出错时继续下一步
On Error Resume Next For i = 1 To Worksheets.Count Sheets(i).Shapes("Option Button 1").ControlFormat.Value = xlOn 'opt button reset Sheets(i).Shapes("CheckBox1").ControlFormat.Value = xlOff 'cb reset Next i
循环遍历对象并匹配名称
For i = 1 To Worksheets.Count For Each myControl In Sheets(i).Shapes If myControl.Name = "CheckBox1" Then myControl.Value = xlOff ElseIf myControl.Name = "Option Button 1" Then myControl.Value = xlOn End If Next myControl Next i