简体   繁体   English

Excel VBA-参考图数据按名称而不是索引号指向

[英]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? 是否可以在VBA中通过其名称引用数据点?

With is a simple Gantt chart that looks like this: With是一个简单的甘特图,看起来像这样:

在此处输入图片说明

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: 您可以通过以下方式更改点B的颜色:首先返回XValue,与您要查找的名称匹配,然后设置相应的点颜色:

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 结果

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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