Search code examples
excelvbaexcel-charts

Deleting title from all graphs and charts


I wrote a very simple code to delete all titles from graphs. It works sometimes, but some other times nothing happens.

    Sub changeformatting()

For Each Sht In Application.Worksheets
    For Each cht In Sht.ChartObjects
        cht.Height = Application.InchesToPoints(6)
        cht.Width = Application.InchesToPoints(9)
        cht.Chart.ChartArea.Format.TextFrame2.TextRange.Font.Size = 10
        cht.Chart.ChartArea.Format.TextFrame2.TextRange.Font.Name = "arial"
        cht.Chart.ChartTitle.Format.TextFrame2.TextRange = Delete


 On Error Resume Next
 
    Next cht
Next Sht

End Sub

I have workbooks with 20-30 graphs, and I would like to automise all the abovementioned stuff. When I create a sample file, with two graphs it works fine, on my big file, it gives an error if all graphs doesn't have a title.

The error code I get is "the object has no title".

Any idea how to fix this? I tried adding on error resume next, but doesnt seem to help.

When I debugg it obviously gives error for the delete row.


Solution

  • To delete the chart title, instead of deleting the The TextFrame2, delete the actual title. Also the delete method will fail if there is no title present.

    Check if the chart has title and then delete it. For example try this.

    If cht.Chart.Hastitle then cht.Chart.ChartTitle.Delete