使用vba根据条件更改图表系列的颜色

时间:2017-12-01 11:31:37

标签: excel vba

我正在尝试使用vba进行编码,以便根据特定条件格式化图表上的系列。我的编码如下

Sub CreateChart()
Dim NPOINTS As Integer
Dim NVAL(1000) As Range, XVAL(1000) As Range, YVAL(1000) As Range
Dim Score(1000) As Range
Sheets("Scenario").Select
Range("B4").Select

NPOINTS = Worksheets("Scenario").Range(Selection, Selection.End(xlDown)).Rows.Count
Set Scenario = Worksheets("Scenario")
ActiveSheet.Shapes.AddChart2(240, xlXYScatter).Select

 NVAL0 = "B3"
 XVAL0 = "C3"
 YVAL0 = "D3"
 SCORE0 = "E3"
 For i = 1 To NPOINTS
       Set Score(i) = Cells(Range(SCORE0).Offset(i, 0).Row, Range(SCORE0).Column)
       Set NVAL(i) = Cells(Range(NVAL0).Offset(i, 0).Row, Range(NVAL0).Column)
       Set XVAL(i) = Cells(Range(XVAL0).Offset(i, 0).Row, Range(XVAL0).Column)
       Set YVAL(i) = Cells(Range(YVAL0).Offset(i, 0).Row, Range(YVAL0).Column)
       Scorei = Score(i).Value
       ActiveChart.SeriesCollection.NewSeries
       ActiveChart.FullSeriesCollection(i).Name = NVAL(i)
       ActiveChart.FullSeriesCollection(i).XValues = XVAL(i)
       ActiveChart.FullSeriesCollection(i).Values = YVAL(i)
       If Scorei <= 10 >= 0 Then
          ActiveChart.SeriesCollection(i).Points.Interior.Colour = _
             RGB(0, 255, 0) 'Green
       ElseIf Scorei <= 30 >= 11 Then
          ActiveChart.SeriesCollection(i).Points.Interior.Colour = _
             RGB(0, 255, 0) 'Green
       ElseIf Scorei <= 60 >= 31 Then
          ActiveChart.SeriesCollection(i).Points.Interior.Colour = _
             RGB(0, 255, 0) 'Green
       ElseIf Scorei <= 100 >= 61 Then
          ActiveChart.SeriesCollection(i).Points.Interior.Colour = _
             RGB(0, 255, 0) 'Green
       Else
          MsgBox "ERROR :- Score out of range"
       End If


 Next
 With ActiveChart
    'chart name
   .HasTitle = False

    'X axis name
   .Axes(xlCategory, xlPrimary).HasTitle = True
   .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "INFLUENCE"
    'y-axis name
   .Axes(xlValue, xlPrimary).HasTitle = True
   .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "IMPORTANCE"
   .SetElement (msoElementLegendRight)
   .Location Where:=xlLocationAsNewSheet, Name:="Priority Chart"
End With
End Sub 

不幸的是,当我运行它时,它失败并且“对象不支持此属性或方法,然后当我按下Debug时它突出显示以下行

ActiveChart.SeriesCollection(i).Points.Interior.Colour = _
             RGB(0, 255, 0) 'Green 

我哪里错了? 我感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

只是

ActiveChart.SeriesCollection(i).format.Fill.ForeColor.RGB =RGB(0, 255, 0)

答案 1 :(得分:0)

.Points()是一个集合。 您需要循环遍历其所有元素并逐个更改颜色。 最左边的点是.Points(1),最右边的点是.Points.count 根据:Change the Point Color in chart excel VBA

也没有内点颜色这样的东西。 根据{{​​3}}

有4个相关选项
  • MarkerBackgroundColor
  • MarkerBackgroundColorIndex
  • MarkerForegroundColor
  • MarkerForegroundColorIndex

根据Jon Peltier的评论,不建议使用colorindex,因为这是excel的遗产&lt; 2003