Home » excel » excel – VBA: Skip looking for an object if not found

excel – VBA: Skip looking for an object if not found

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m working in Excel on a sheet where users can enter information into specific cells, save, then send. In this sheet they have the option of pasting an image (a .bmp file named “Picture”) as well. I have a macro that clears the contents of the cells. When the image is present it works fine, but fails when the image is not present, which it won’t always be. I have zero coding experience and cobbled everything together so far from Google. How do I get my macro to skip looking for the named image if it’s not on the sheet but continue to clear the contents of the remaining cells?

Here is my code:

Sub ResetandDelete()
' 
'ResetAndDelete Macro
'Clears cell contents and resets form.

    Range("A44:E60").Select
    Selection.ClearContents
    Activesheet.Shapes.Range(Array("Picture")).Select
    Selection.Delete
    Range("C6:C38").Select
    Selection.ClearContents

End Sub

Please help!!

How to&Answers:

Try this

Sub ResetandDelete()
    With ActiveSheet
        .Range("A44:E60").ClearContents

        On Error Resume Next
        .Shapes.Range(Array("Picture")).Delete
        On Error GoTo 0

        .Range("C6:C38").ClearContents
    End With
End Sub