VBA Excel:一个线图中的不同颜色取决于值

问题描述 投票:0回答:1

我正在寻找一种在Excel的图表的相同折线图中有三种不同颜色的方法,具体取决于值本身或它们来自何处(来自哪个表格f.e)。

直到现在,我有以下代码:

Sub ChangeColor()
Dim i As Integer
Dim IntRow As Integer
Dim r As Range

ActiveSheet.ChartObjects("Cash").Activate
ActiveChart.SeriesCollection(1).Select

IntRow = ActiveChart.ChartObjects("Cash").Count

For i = 2 To IntRow
    Set r = Cells(2, i)
    If r.Value < 3000 Then
        Selection.Border.ColorIndex = 5
    Else
        Selection.Border.ColorIndex = 9 
    End If
Next
End Sub

但是,不考虑if语句,只有在我更改第一个ColorIndex时,整行的颜色才会改变。我不知道如何根据底层表中的值对行的部分进行着色。

此外,通过将IntRow定义为ActiveChart.ChartObjects("Cash").Count,我无法获得数组的长度。这个问题可以通过手动计数和将IntRow声明为整数来解决,但是,上面的版本似乎更好(如果可能的话)。

我感谢任何帮助!谢谢。

亚历山德拉

excel vba excel-vba charts
1个回答
2
投票

您可以直接从图表系列中读取值:

Sub ChangeColor()
    Dim cht As Chart, p As Point, s As Series
    Dim i As Integer
    Dim numPts As Long

    'access the chart directly - no select/activate required
    Set cht = ActiveSheet.ChartObjects("Cash").Chart

    'reference the first series
    Set s = cht.SeriesCollection(1) 

    'how many points in the first series?
    numPts = s.Points.Count

    'loop over the series points
    For i = 1 To numPts

        Set p = cht.SeriesCollection(1).Points(i)

        p.Border.ColorIndex = IIf(s.Values(i) < 3000, 5, 9)

    Next
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.