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

15

我正在编写一些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

1
这是图表对象模型的一个缺陷。使用 .Format.Line 语法将相同的格式应用于标记线和连接线。使用 .Border 将颜色应用于连接线,.MarkerForegroundColor 应用于标记线。 - Jon Peltier
3个回答

27

连接线的颜色是 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

ActiveChart 是一个散点图,并且这是在Excel 2007中测试的。


感谢回复。@Axel,你提出的技巧对我也起作用了。谢谢。 - Bob Smith
非常感谢您的努力破解.Line.Visible。我在 Excel 2010 中的收藏品中有第一种系列没有显示线条,添加 msoFalse 在 msoTrue 前解决了这个问题! - zoagli
1
从Excel 2013开始,标记线之间的线条显然是使用.Border属性设置的。在我意识到发生了什么之前,花费了一个小时尝试您的建议! - Steve can help

10
从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

NB:如果您使用Selection.Format.Line.Weight,请注意默认情况下它适用于边框和连接线的粗细。


2
.Border.MarkerBackgroundColor.MarkerForegroundColor是旧版Excel 97-2003对象模型的遗留部分。它们应该被LineFormatFillFormat所取代,但这些在Office 2007中实现不完全,在Office 2016中仍未得到修正。 - Jon Peltier

0

您可以使用

ActiveChart.SeriesCollection(1).MarkerForegroundColor = -2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接