Search code examples
vbaexcelgraph

VBA code to apply only the last data label


I don't speak English very well, but I hope you can understand me.

It's about a VBA code for plotting graphs. I am trying to automate my sheets and I found a simple and easy code in the internet to do so. After updating the series, my intention is to clear all data labels except for the last one.

The code is:

Dim oChart As ChartObject
Dim MySeries As Series

For Each oChart In ActiveSheet.ChartObjects
 For Each MySeries In oChart.Chart.SeriesCollection

    'Clear Existing Data Labels
       MySeries.ApplyDataLabels (xlDataLabelsShowNone)
       
    'Apply Labels to Last Point
        MySeries.points(MySeries.points.Count).ApplyDataLabels
   
    Next MySeries
Next oChart

End Sub

But, this code runs for only three of the ten graphs, and doesn't work for the others. I've looked for similarities or differences among the series (like the name format or type of graphic - line, bar, pie) but I could not find the problem

The first part of the macro which is delete all data labels works correctly for all the graphs, though. I also tried to do it for more than one sheet and workbook, also unsuccessfully.


Solution

  • You should over every-sheet, every chart, every series and points. ApplyDataLabels is a property a point not series or multiple points. xlDataLabelsShowNone Doesn't mean none of the points. It means that the label will not be shown in any format. You can read about this Object here.

    Code below would do the job for you.

    Sub remove_label()
    
        Dim wsh As Worksheet
        Dim oChart As ChartObject
        Dim MySeries As Series
        Dim oPoints As Points
        Dim MyPoint As Point
        Dim i As Long
    
         For Each wsh In ThisWorkbook.Worksheets
           For Each oChart In wsh.ChartObjects
             For Each MySeries In oChart.Chart.SeriesCollection
               Set oPoints = MySeries.Points
                 i = oPoints.Count
                    For Each MyPoint In oPoints
                      i = i - 1
                        If i <> 0 Then
                         'Clear Existing Data Labels
                          MyPoint.ApplyDataLabels xlDataLabelsShowNone
                        Else
                         'Apply Labels to Last Point
                          MyPoint.ApplyDataLabels xlDataLabelsShowValue
                        End If
    
               Next MyPoint
             Next MySeries
           Next oChart
         Next wsh
    
    End Sub