VBA Excel select & delete all shapes with the same ID and remove

夙愿已清 提交于 2021-02-11 02:49:34

问题


I would like to delete all the shapes from my sheet. They have the same ID.

I found two codes:

The first one:

Public Sub ActiveShapes()
    Dim ShpObject As Variant

    If TypeName(Application.Selection) = "Firestop" Then
        Set ShpObject = Application.Selection
        ShpObject.Delete
    Else
        Exit Sub
    End If
End Sub

is not working. There are no errors, but also no reaction at all.

The second one: Selecting a shape in Excel with VBA

 Sub Firestopshapes()
     ActiveSheet.Shapes("Firestop").Delete
 End Sub

works, but remove only one by one element. In my event, all the elements have the "Firestop" ID. I would like to make them all deleted at once. How can I do that?


回答1:


The issue is thet If TypeName(Application.Selection) = "Firestop" Then is never true. Have a look into the TypeName function does not return the name of the Application.Selection but instead it returs what type Application.Selection is. Here it probably returns Object because a shape is an object.

Actually names are unique. You cannot add 2 shapes with the same name. That is why ActiveSheet.Shapes("Firestop").Delete only deletes one shape.

There seems to be a bug that when you copy a named shape 2 shapes with the same name exist (which should not be possible). You can get around this by deleting that shape in a loop until you get an error (no shape with that name is left).

On Error Resume Next
Do
    ActiveSheet.Shapes("Firestop").Delete
    If Err.Number <> 0 Then Exit Do
Loop
On Error GoTo 0 'don't forget this statement after the loop



回答2:


It is not recommended to use On Error Resume Next often. We recommend using it only when it is indispensable.

Sub test()
    Dim shp As Shape
    Dim Ws As Worksheet

    Set Ws = ActiveSheet
    For Each shp In Ws.Shapes
        If shp.Name = "Firestop" Then
            shp.Delete
        End If
    Next shp
End Sub


来源:https://stackoverflow.com/questions/60433388/vba-excel-select-delete-all-shapes-with-the-same-id-and-remove

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!