【问题标题】:VBA Loop through graphs setting chart type (xlLine), series weight, series colors, chart legend (down), Chart height and widthVBA循环图表设置图表类型(xlLine),系列重量,系列颜色,图表图例(向下),图表高度和宽度
【发布时间】:2020-03-20 16:05:31
【问题描述】:

在尝试使用 makro 来格式化我的图表时,我经常遇到错误。我想要做的是:循环通过工作表和图表设置图表类型(xlLine)、系列权重、系列颜色、图表图例(向下)、图表高度和宽度。

我正在尝试使用以下代码:

Sub LoopThroughCharts()

Dim sht As Worksheet
Dim CurrentSheet As Worksheet
Dim cht As ChartObject

Application.ScreenUpdating = False
Application.EnableEvents = False

Set CurrentSheet = ActiveSheet

For Each sht In ActiveWorkbook.Worksheets
  For Each cht In sht.ChartObjects
    cht.Activate

    ActiveChart.ChartType = xlLine


  ActiveChart.SeriesCollection(1).Select
With Selection.Format.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(214, 198, 138)
    .Weight = 1.5

  ActiveChart.SeriesCollection(2).Select
With Selection.Format.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(5, 34, 61)
    .Weight = 1.5
End With

 Next cht
Next sht

CurrentSheet.Activate
Application.EnableEvents = True

End Sub

目前我在代码末尾的“Next cht”上收到编译错误,第一行“Sub LoopThroughCharts()”变成黄色。

对如何克服这个错误有什么建议吗?

此外,它在较早的状态似乎停止在ActiveChart.SeriesCollection(2).Select

这似乎是因为有些图表只有 1 个系列。您是否也有关于如何克服这个问题的建议,因为在某些时候我会在另一个工作簿中循环它,其中包含许多图表和不同数量的系列。

刚开始学习 VBA 编码。

【问题讨论】:

  • 您缺少End With。你可以用这个smart indenter来修复你的缩进,应该会更清晰。

标签: excel vba loops charts formatting


【解决方案1】:

不要这样做:

  cht.Activate

您无需激活即可直接使用cht。

例如,而不是这个:

  ActiveChart.SeriesCollection(1).Select
  With Selection.Format.Line

使用这个:

  With cht.Chart.SeriesCollection(1).Format.Line '<< EDIT added Chart

测试:

Sub LoopThroughCht()

    Dim sht As Worksheet
    Dim co As ChartObject, cht As Chart

    Application.ScreenUpdating = False

    For Each sht In ActiveWorkbook.Worksheets
        For Each co In sht.ChartObjects

            Set cht = co.Chart
            cht.ChartType = xlLine

            With cht.SeriesCollection(1).Format.Line
                .Visible = msoTrue
                .ForeColor.RGB = RGB(214, 198, 138)
                .Weight = 1.5
            End With

            If cht.SeriesCollection.Count > 1 Then
                With cht.SeriesCollection(2).Format.Line
                    .Visible = msoTrue
                    .ForeColor.RGB = RGB(5, 34, 61)
                    .Weight = 1.5
                End With
            End If

        Next co
    Next sht
End Sub

【讨论】:

  • 谢谢,但它似乎消除了错误。对此有什么想法吗?
  • 你解决了 BigBen 的评论吗?
  • 其实我之前没有看到那个评论,但是在做了你的两个建议之后,我仍然在倒数第四行“Next cht”出现错误(编译错误:Next without For)...此外,在我添加第二个 seriesCollection 之前,一开始似乎有效。
  • 我在代码中打错了字 - 请参阅上面的更正。不过,更新您的帖子以添加您当前的代码会有所帮助:我们无法判断您所做的更改。
  • 谢谢我刚刚做了,之后也会实施您的更正
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多