Mary
Mary

Reputation: 788

Delete graphs VBA Error

How do I get VBA to ignore this code when there are no graphs on the worksheet? At the moment, unless there is a ChartObject in the worksheet, it will stop and open the debugger.

ActiveSheet.ChartObjects.Delete

Thank you.

Upvotes: 1

Views: 9253

Answers (2)

Robert Co
Robert Co

Reputation: 1715

Instead of ignoring the code, why not just ignore the error.

On Error Resume Next
ActiveSheet.ChartObjects.Delete
On Error GoTo 0

Upvotes: 5

Siddharth Rout
Siddharth Rout

Reputation: 149295

How do I get VBA to ignore this code when there are no graphs on the worksheet?

Try this

Sub Sample()
    Dim ws As Worksheet
    Dim Chrtobj As ChartObject

    Set ws = ThisWorkbook.Sheets("Sheet1")

    '~~> Check if there are any chartobjects in the sheet
    If Not ws.ChartObjects.Count = 0 Then ws.ChartObjects.Delete
End Sub

Upvotes: 4

Related Questions