2015-04-16 525 views
5

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

任何想法如何区分代码中的线条颜色和标记线颜色?

创建该代码时,我记录自己改变标记线时我记录自己改变线的颜色连接标记的创建

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 
+0

可能取决于版本,但可能的答案大概是“你不行”。但是http://peltiertech.com/conditional-formatting-of-lines-in-an-excel-line-chart-using-vba/可能会有所帮助。 – pnuts

+1

这是图表对象模型的一个缺点。使用.Format.Line语法对标记线和连接线应用相同的格式。使用.Border将颜色应用于连接线并将.MarkerForegroundColor应用于标记线。 –

回答

11

的连线的线颜色为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测试的。

+0

感谢您的回复。 @Axel,你的建议技巧也适用于我。谢谢。 –

+0

非常感谢你从我的内心深处挖掘.Line.Visible的黑客。我有一个集合中的第一个系列没有显示该行(在Excel 2010中)。在msoTrue之前添加msoFalse的窍门! – zoagli

+0

从Excel 2013中,标记之间的界限显然是使用.Border属性设置的。在我意识到发生了什么事之前,花了我一小时的时间尝试您的建议! –

2

从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的,注意,这适用于边界和连接线厚度都默认

+0

'.Border','.MarkerBackgroundColor'和'.MarkerForegroundColor'是旧的Excel 97-2003对象模型的遗留位。它们应该被'LineFormat'和'FillFormat'替代,但是这些在Office 2007中未得到完全实现,而在Office 2016中仍未得到纠正。 –

0

你可以使用

ActiveChart.SeriesCollection(1).MarkerForegroundColor = -2