VBA 使用 ColorIndex 更改图表的线条颜色

VBA Change Line Color of Chart with ColorIndex

下面的代码有效并使用 rgb 的三个值设置了四行的颜色。三个rgb值填在一个数组中(Clr),不是很清楚。是否有另一种方法可以通过使用 Hex 数字、ColorIndexvbBlack 等预定义颜色来即时显示?

Sub CreateChart()
Dim i As Long
Dim j As Long
Dim Clr() As Variant

'Clr = Array("vbBlack", "vbBlue", "vbRed", "vbCyan", "vbGreen", "vbMagenta")    ' colors as types
'Clr = Array("&H0", "&HFF0000", "&Hff", "&HFFFF00", "&HFF00", "&HFF00FF")       ' Hex of colors as String
'Clr = Array(&H0, &HFF0000, &HFF, &HFFFF00, &HFF00, &HFF00FF)                   ' Hex Values of colors
'Clr = Array(&H0, &HFF0000, &HFF, &HFFFF00, &HFF00, &HFF00FF)                   ' IndexColor
Clr = Array(0, 0, 0, 0, 0, 255, 255, 0, 0, 0, 255, 255, 0, 255, 0, 255, 0, 255)
With Charts.Add
    .ChartType = xlXYScatterLinesNoMarkers
    .SetSourceData Source:=Sheets("Plot").Range("A12:E213")
    j = 0
    For i = 2 To 5
        With .FullSeriesCollection(i - 1).Format.Line
            .ForeColor.RGB = RGB(Clr(j), Clr(j + 1), Clr(j + 2))
            j = j + 3
        End With
    Next
End With
   
End Sub

使用 Hex2Dec() WorkSheetFunction ?

Sub CreateChart()
    Dim i As Long
    Dim j As Long
    Dim Clr() As Variant

    'Clr = Array("vbBlack", "vbBlue", "vbRed", "vbCyan", "vbGreen", "vbMagenta")    ' colors as types
    'Clr = Array("&H0", "&HFF0000", "&Hff", "&HFFFF00", "&HFF00", "&HFF00FF")       ' Hex of colors as String
    Clr = Array(&H0, &HFF0000, &HFF, &HFFFF00, &HFF00, &HFF00FF)                   ' Hex Values of colors
    'Clr = Array(&H0, &HFF0000, &HFF, &HFFFF00, &HFF00, &HFF00FF)                   ' IndexColor
    'Clr = Array(0, 0, 0, 0, 0, 255, 255, 0, 0, 0, 255, 255, 0, 255, 0, 255, 0, 255)
    With Charts.Add
        .ChartType = xlXYScatterLinesNoMarkers
        .SetSourceData Source:=Sheets("Plot").Range("A12:E213")
        j = 0
        For i = 2 To 5
            With .FullSeriesCollection(i - 1).Format.Line
                .ForeColor.RGB = WorksheetFunction.Hex2Dec(Clr(j))
                j = j + 1
            End With
        Next i
    End With
End Sub

实际上,您的代码运行良好,只是去掉引号和 RGB 函数。十六进制值也没有问题,它们工作正常。

Sub CreateChart()
Dim Color As Variant
Dim Source as Range
Dim i As Long

    Set Source = Sheets("Plot").Range("A12:E213")
    Color = Array(vbBlack, vbBlue, vbRed, vbCyan, vbGreen, vbMagenta)
    ' Array(&H0, &HFF0000, &HFF, &HFFFF00, &HFF00, &HFF00FF) works as well
    With Charts.Add
        .ChartType = xlXYScatterLinesNoMarkers
        .SetSourceData Source
        For i = 1 To .FullSeriesCollection.Count
            .FullSeriesCollection(i).Format.Line.ForeColor.RGB = Color(i - 1)
        Next i
    End With

End Sub

要使用 Color(i) 而不是有些笨拙的 Color(i - 1) 我们应该添加 Option Base 1 以默认从 1 开始 Array 索引。但这当然取决于您。

P.S。看看xlRGBColor enumeration