vba 删除excel工作表中除表单控件外的所有形状

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12789499/
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-08 14:10:02  来源:igfitidea点击:

Delete all shapes in excel worksheet except form controls

excelexcel-vbavba

提问by marillion

I have an excel worksheet where a macro tied to a button draws dynamic shapes based on the user input parameters in the worksheet.

我有一个 excel 工作表,其中绑定到按钮的宏根据工作表中的用户输入参数绘制动态形状。

I am trying to write a new macro to clean the sheet, or in other words delete all shapes in the worksheet.

我正在尝试编写一个新的宏来清理工作表,或者换句话说,删除工作表中的所有形状。

I tried using the code below, and it indeed deletes all shapes, however button form controls also get deleted in the process. Is there an easy way to only get rid of the shapes (arrows, textboxes, ellipses etc.) in the worksheet? Thanks a bunch!!!

我尝试使用下面的代码,它确实删除了所有形状,但是按钮表单控件也在此过程中被删除。有没有一种简单的方法可以只去掉工作表中的形状(箭头、文本框、椭圆等)?谢谢一堆!!!

Sub DeleteAllShapes()

Dim Shp As Shape

For Each Shp In ActiveSheet.Shapes
    Shp.Delete
Next Shp

End Sub

回答by Jamie Bull

To delete autoshapes and textboxes only you can use:

要仅删除自动图形和文本框,您可以使用:

Sub DeleteAllShapes()

Dim Shp As Shape

For Each Shp In ActiveSheet.Shapes
    If Shp.Type = msoAutoShape Or Shp.Type = msoTextBox Then Shp.Delete
Next Shp

End Sub

Alternatively you can work the other way around and specify the types not to delete. You can use the enumerated types but it's more readable to use the type names. The following snippet will delete everything apart from Form Controls and OLE control objects.

或者,您可以反过来工作并指定不删除的类型。您可以使用枚举类型,但使用类型名称更具可读性。以下代码段将删除除表单控件和 OLE 控件对象之外的所有内容。

Sub DeleteAllShapes()

Dim Shp As Shape

For Each Shp In ActiveSheet.Shapes
    If Not (Shp.Type = msoOLEControlObject Or Shp.Type = msoFormControl) Then Shp.Delete
Next Shp

End Sub

A full list of MSO Shape Types. http://msdn.microsoft.com/en-us/library/office/aa432678(v=office.12).aspx

MSO 形状类型的完整列表。 http://msdn.microsoft.com/en-us/library/office/aa432678(v=office.12).aspx

Ron de Bruin has a good collection of snippets which may be relevant to anyone else coming across this question. http://www.rondebruin.nl/controlsobjectsworksheet.htm

Ron de Bruin 收集了很多可能与遇到此问题的其他人相关的片段。 http://www.rondebruin.nl/controlsobjectsworksheet.htm