删除一组 VBA 按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8898976/
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
Deleting a collections of VBA buttons
提问by James
I'm using the following script to produce buttons in excel, the range is just where I'd like it to be placed.
我正在使用以下脚本在 excel 中生成按钮,范围就是我想要放置它的位置。
Sub CreateAddButton(rng As Range)
Dim btn As Button
With Worksheets("User")
Set btn = .Buttons.Add(rng.Left, rng.Top, rng.width, rng.Height)
With btn
.name = "Add"
.Caption = "Add Column"
.OnAction = "CreateVariable"
End With
End With
End Sub
Only problem is, I'd like a method which can delete all the buttons produced by this method? I want to steer away from global variables if possible. Any help would be gratefully received. James
唯一的问题是,我想要一种可以删除此方法生成的所有按钮的方法?如果可能,我想避开全局变量。任何帮助将不胜感激。詹姆士
采纳答案by brettdj
I'd suggest Tim's method using a specific name - which does't need a global variable. For example you could add a "_||ForDeletion"suffix to each button name and then look for it on a delete routine
我建议使用特定名称的 Tim 方法 - 不需要全局变量。例如,您可以为每个按钮名称添加“_||ForDeletion”后缀,然后在删除例程中查找它
.Name = "Add_||ForDeletion"
A Forms
button does provide another alternative though (no pun intended), you can store a text sting in the AlternativeText
under "Properties" then "Web" and use this as an identifier for a delete routine.
一个Forms
按钮确实提供了另一种选择,但(没有双关语意),你可以存储文本在刺AlternativeText
“属性”,然后在“网络”下,并以此作为删除程序的标识符。
The delete routine at bottom works backwards to avoid errors when looping through a range
底部的删除例程向后工作以避免在循环范围内时出错
Sub TesMe()
Call CreateAddButton([a2])
End Sub
Sub CreateAddButton(rng As Range)
Dim btn As Button
With Worksheets("User")
Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
With btn
.Name = "Add"
.Caption = "Add Column"
.OnAction = "CreateVariable"
.ShapeRange.AlternativeText = "MyCollection"
End With
End With
End Sub
Sub GetMyButtons()
Dim btns As Object
Dim lngRow As Long
Set btns = Sheets("User").Buttons
For lngRow = btns.Count To 1 Step -1
If btns(lngRow).ShapeRange.AlternativeText = "MyCollection" Then
MsgBox "Found one", vbCritical
btns(lngRow).Delete
End If
Next
End Sub
回答by Jesse
Buttons in VBA are in the Shapes collection. You can use:
VBA 中的按钮位于 Shapes 集合中。您可以使用:
Sub deleteButtons()
Dim btn As Shape
For Each btn In ActiveSheet.Shapes
If btn.AutoShapeType = msoShapeStyleMixed Then btn.Delete
Next
End Sub
msoShapeStyleMixed seems to be the type for all Form and ActiveX controls.
msoShapeStyleMixed 似乎是所有 Form 和 ActiveX 控件的类型。