Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

vba - Delete all shapes in excel worksheet except form controls

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...