Search code examples
excelvbacharts

Getting the name of point in chart series


Hi I can't seem to get the names of my chart it always returns S1P1. Am I missing something or doing something wrong?

Dim pointNames As String
Dim pointEntryIndex As Integer
            For pointEntryIndex = 1 To ActiveChart.FullSeriesCollection(1).Points.Count
                ActiveChart.FullSeriesCollection(1).Points(pointEntryIndex).Select
                pointNames = ActiveChart.FullSeriesCollection(1).Points(pointEntryIndex).Name
                Debug.Print pointNames
            
            Next pointEntryIndex

Solution

  • As written in the comment, the name of a point is in the form SxPy with x = series number and y = point number. This name is given by Excel automatically and cannot be changed (it is a read only property).

    You wrote in the comment that you want to access the DataLabel of a point. That's rather easy. Every point has a property DataLabel - but you need to check if data labels are switched on for that point. For that, you can use the property HasDataLabel. If this is False and you access DataLabel, you will get a runtime error.

    You can ensure that data labels are switched on by using the method ApplyDataLabels for the data series.

    Have a look to the following code. You will notice that I use intermediate variables for chartObject, chart, Series and Point. This is not a must, but it helps to debug the code, and I often use the Locals Window (View->Locals Window) to inspect the objects and learn about the properties.

    Dim co As ChartObject, ch As Chart
    ' Change this to whatever chart you want to deal with.
    Set co = ThisWorkbook.Worksheets(1).ChartObjects(1)
    Set ch = co.Chart
    
    Dim seriesIndex As Long
    For seriesIndex = 1 To ch.FullSeriesCollection.Count
        Dim ser As Series
        Set ser = ch.FullSeriesCollection(seriesIndex)
        ' This switches on the DataLabels for the series
        ser.ApplyDataLabels
    
        Dim pointEntryIndex As Integer
        For pointEntryIndex = 1 To ser.Points.Count
            Dim p As Point
            Set p = ser.Points(pointEntryIndex)
            If p.HasDataLabel Then
                Debug.Print p.DataLabel.Caption
                ' You can set the Caption to whatever you want.
                p.DataLabel.Caption = "Hi" & seriesIndex & "." & pointEntryIndex
            End If
        Next pointEntryIndex
    Next seriesIndex