简体   繁体   中英

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?

With is a simple Gantt chart that looks like this:

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM