Search code examples
excelexcel-2003vba

Check if Autoshape exists


I am trying to create a simple macro to delete some data including an Autoshape - Shapes("ACCESS"), but I would like this macro to run only if Autoshape exists.

If it doesn't exist, the action would be just Range("B2").Select

Can anybody help please?

My Code

Sub DeleteRepWT()

ActiveSheet.Shapes("ACCESS").Select
Selection.ShapeRange.IncrementLeft 57#
Selection.ShapeRange.IncrementTop -85.5
Range("M4").Select
ActiveSheet.Shapes("ACCESS").Select
Selection.Delete
Columns("K:AI").Select
Selection.Delete Shift:=xlToLeft
Range("B2").Select

End Sub

Solution

  • You can use an object type shape, in my code it's Shp, and try to set it to Set Shp = ActiveSheet.Shapes("ACCESS").

    Add On Error Resume Next before trying to Set the shape object (so won't get a run-time error), and after trying to Set the shape, you can check If Shp Is Nothing, which means checking if you were able to Set the shape (if you weren't, it means there is no Shapes("ACCESS") in your worksheet).

    Code

    Option Explicit
    
    Sub DeleteRepWT()
    
    Dim Shp As Shape
    
    On Error Resume Next
    Set Shp = ActiveSheet.Shapes("ACCESS") ' try to set the object to "ACCESS"
    On Error GoTo 0
    
    If Shp Is Nothing Then ' if there is no Shapes("ACCESS")
        Range("B2").Select 
    Else ' shape exists
        With Shp
            ' rest of your original code here ...
    
        End With
    End If
    
    End Sub