Search code examples
vbaexcelexcel-charts

Excel VBA - Reference chart data point by name instead of index number


I have a basic Gantt chart with a table as its data source, however, when another name is selected somewhere on the sheet, this table gets emptied and refilled with the data that belongs to the chosen name.

There is one data point the same for every name and I want its bar to have another color.

I know about this way to reference a data point:

ActiveChart.FullSeriesCollection(2).Points(3)

But that wont work in my example because the amount of data points keeps changing and the same thing is not always in the third position.

I tried this, but like I thought it throws me a type mismatch error:

ActiveChart.FullSeriesCollection(2).Points("SomeString")

Is it possible to reference a data point by its name in VBA?


Solution

  • With is a simple Gantt chart that looks like this:

    enter image description here

    You can change the color of point B by first returning the XValue, match against the name your looking for and then set the corresponding point color:

    Option Explicit
    
    Sub ChangePointBColor()
        Dim x As Integer
        Dim varValues As Variant
        Dim cht As Chart
        Set cht = Worksheets("Sheet1").ChartObjects("Chart 3").Chart
    
        With cht.SeriesCollection(2) 
            varValues = .XValues
    
            For x = LBound(varValues) To UBound(varValues)
                If varValues(x) = "B" Then
                    .Points(x).Interior.Color = RGB(140, 125, 230)
                End If
            Next x
        End With
    End Sub
    

    Result

    enter image description here