VBA-更改图表线条颜色

时间:2018-10-08 17:49:11

标签: excel vba

我一直在尝试获取一个VBA脚本,该脚本将根据RGB参考值来更新图表线条颜色,而RGB参考值会根据得分而变化。

我也想了解:

  1. 如何从更新中排除某些工作表
  2. 如何从更新中排除某些系列(它们始终保持灰色)

我当前的脚本是:

Sub UpdateAllChartLines

Dim sht As Worksheet
Dim CurrentSheet As Worksheet
Dim cht As ChartObject
Dim ser As Series

Application.ScreenUpdating = False
Application.EnableEvents = False

Set CurrentSheet = ActiveSheet
Set myRed = Worksheets("TextElements").Range("K6")
Set myGreen = Worksheets("TextElements").Range("K7")
Set myBlue = Worksheets("TextElements").Range("K8")
Set myThickness = Worksheets("TextElements").Range("E37")

For Each sht In ActiveWorkbook.Worksheets
  For Each cht In sht.ChartObjects
    For Each ser In cht.SeriesCollection
        cht.Activate
                With ActiveChart.SeriesCollection
                .Format.Line.Visible = msoFalse
                .Format.Line.Visible = msoTrue
                .Format.Line.ForeColor.RGB = RGB(myRed, myGreen, myBlue)
                .Format.Line.Weight = myThickness
                 End With
    Next ser
   Next cht
Next sht

CurrentSheet.Activate
Application.EnableEvents = True

End Sub

我最近的问题是

出现调试错误
For Each ser In cht.SeriesCollection

任何帮助,我们都感激不尽。

2 个答案:

答案 0 :(得分:0)

您需要澄清要基于什么基础排除事物,但是类似的事情应该起作用。

请注意,无需激活/选择任何内容即可进行更改。

Sub UpdateAllChartLines()

    Dim sht As Worksheet
    Dim chtObj As ChartObject
    Dim ser As Series
    Dim clr As Long, sNum

    Application.ScreenUpdating = False

    With Worksheets("TextElements")
        clr = RGB(.Range("K6").Value, .Range("K8").Value, .Range("K8").Value)
        myThickness = .Range("E37").Value
    End With

    For Each sht In ActiveWorkbook.Worksheets
        If sht.Name <> "IgnoreThis" Then '<<< can exclude sheets here
            For Each chtObj In sht.ChartObjects
                For Each sNum in Array(5,6,7,8) '<<<edit
                'For Each ser In chtObj.Chart.SeriesCollection

                        With chtObj.Chart.SeriesCollection(sNum)
                            .Format.Line.Visible = msoTrue
                            .Format.Line.ForeColor.RGB = clr
                            .Format.Line.Weight = myThickness
                        End With

                'Next ser
                Next sNum
            Next chtObj
        End If
    Next sht

End Sub

答案 1 :(得分:0)

我已将蒂姆的回答标记为答案,但我想我会在最终的工作脚本中加入以帮助将来的任何人。我怀疑可以对此进行简化,但是由于未知原因,我也无法将其与ser.name = x OR y OR z Then一起使用Tim的答案也添加了标记到每个图的第一个序列上,但是通过添加{{1 }}命令。

再次感谢蒂姆和其他发表评论的人。

J

.MarkerStyle = xlMarkerStyleNone