Excel VBA颜色代码XY散点图(按三维)

时间:2018-09-23 12:42:56

标签: excel vba

首先,我是VBA的一名新手。我正在尝试编写一个宏,该宏将对具有多个三维尺寸see spreadsheet的多个系列的XY散点图进行颜色编码。为此,我为特定列(在本例中为第I列)中的每个单元格赋予了特定的背景色。现在,我设法使代码与单个系列single series color一起使用。但是,当我添加多个序列时,它将使用该序列中的第一个单元格再次重新开始着色,而不是继续前进至正确的单元格see this image with the wrong colors。例如,如果第二个系列从第53行开始,则需要将单元格I53的颜色分配给第53行中的XY。相反,它将以第一个可用颜色(单元格I2)重新开始。我在这里想念什么?

Sub Colorpoints()

Dim cht As Chart
Dim ser As Series
Dim pnt As Point
Dim i As Long, j As Long, k As Long
Dim rng As Range
Set cht = ActiveChart
Set ser = cht.SeriesCollection(1)
Set rng = ActiveSheet.Range("I:I") ' Each of these cells has a different color

For k = 1 To cht.SeriesCollection.Count
Set ser = cht.SeriesCollection(k)

j = 0

For i = 1 To ser.Points.Count

    j = j + 1

    Set pnt = ser.Points(i)

    pnt.MarkerBackgroundColor = rng(j).Interior.Color ' Cycle through available colors

    If (j > rng.Count) Then j = 0

Next i
Next k

End Sub

1 个答案:

答案 0 :(得分:1)

我添加了一些缩进,现在您可以清楚地看到错误所在。 该语句j = 0是不必要的。如果要使用它,则将其放在For k = 1 To cht.SeriesCollection.Count之前。使用适当的缩进,我会避免很多错误。

更正的代码:

Option Explicit

Sub Colorpoints()

    Dim cht As Chart
    Dim ser As Series
    Dim pnt As Point
    Dim i As Long, j As Long, k As Long
    Dim rng As Range

    Set cht = ActiveChart
    Set ser = cht.SeriesCollection(1)
    Set rng = ActiveSheet.Range("I:I") ' Each of these cells has a different color

    For k = 1 To cht.SeriesCollection.Count

        Set ser = cht.SeriesCollection(k)

        'j = 0  'If you set it to 0 when stepping into another series
                'then obviously it starts colouring from the beginning
                'Just remove it

        For i = 1 To ser.Points.Count

            j = j + 1

            Set pnt = ser.Points(i)

            pnt.MarkerBackgroundColor = rng(j).Interior.Color ' Cycle through available colors

            If (j > rng.Count) Then j = 0

        Next i
    Next k

End Sub