Excel VBA 线条颜色/标记线颜色

Excel VBA Line Color / Marker Line Color

我正在编写一些 VBA 代码来修改 Excel 图表。对于散点图,我需要修改标记线颜色,有时还需要修改连接线的线条颜色。我可以手动执行这两个操作,但是当我录制宏时,尽管结果非常不同,但两个操作都会产生相同的代码。

知道如何在代码中区分线条颜色和标记线颜色吗?

这段代码是我记录自己改变标记线的颜色时创建的

Sub Macro3()
'

    ' Macro3 Macro
    '
    '
        ActiveChart.SeriesCollection(2).Select
        With Selection.Format.Line
            .Visible = msoTrue
            .ForeColor.ObjectThemeColor = msoThemeColorAccent1
            .ForeColor.TintAndShade = 0
            .ForeColor.Brightness = 0
        End With
    End Sub

这段代码是我记录自己改变连接标记线的颜色时创建的

Sub Macro4()
'
' Macro4 Macro
'
'
'Change the Line Color
    ActiveChart.SeriesCollection(2).Select
    With Selection.Format.Line
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorAccent1
        .ForeColor.TintAndShade = 0
        .ForeColor.Brightness = 0
    End With
End Sub

连接线的线条颜色为Series.Format.Line.ForeColor。标记线颜色为 Series.MarkerForegroundColor。但至少在 Excel 2007 中设置 Series.Format.Line.ForeColor 存在问题。参见示例:

Sub Macro3()
 Dim oChart As Chart
 Dim oSeries As Series

 Set oChart = ActiveChart
 Set oSeries = oChart.SeriesCollection(2)

 oSeries.Format.Line.Weight = 5 'Line.Weigth works ever

 oSeries.Format.Line.Visible = msoFalse 'for Line.ForeColor getting to work we have to cheat something
 oSeries.Format.Line.Visible = msoTrue
 oSeries.Format.Line.ForeColor.RGB = RGB(0, 255, 0) 'now it works

 oSeries.MarkerSize = 15
 oSeries.MarkerBackgroundColor = RGB(255, 0, 0) 'marker background

 oSeries.MarkerForegroundColor = RGB(0, 0, 255) 'marker foreground (lines around)
End Sub

A​​ctiveChart 是散点图。这是用 Excel 2007 测试的。

从Excel 2013开始,线条颜色和标记线颜色很容易区分,因为线条颜色是使用.Border 属性,而标记颜色使用 .MarkerBackgroundColor.MarkerForegroundColor 属性设置。

因此,以下内容将为您提供白色标记,标记之间带有红色边框和黑色连接线:

ActiveChart.SeriesCollection(1).Select
With Selection
    .Border.LineStyle = xlContinuous
    .Border.Color = RGB(0,0,0)
    .MarkerBackgroundColor = RGB(255, 255, 255)
    .MarkerForegroundColor = RGB(255, 0, 0)
End With

注意: 如果您使用 Selection.Format.Line.Weight,请注意这适用于边框和连接线粗细默认

你可以使用

ActiveChart.SeriesCollection(1).MarkerForegroundColor = -2