图例格式的录制宏中断

时间:2017-01-25 14:29:42

标签: excel excel-vba vba

Sub Total()
ActiveChart.ClearToMatchStyle
ActiveChart.ChartStyle = 227
ActiveSheet.ChartObjects("Chart 19").Activate
ActiveChart.Legend.Select
ActiveChart.Legend.LegendEntries(1).Select
With Selection.Format.Line
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorText1
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = 0
    .Transparency = 0
End With
ActiveChart.Legend.LegendEntries(5).Select
With Selection.Format.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(255, 255, 0)
    .Transparency = 0
End With
ActiveChart.Legend.LegendEntries(6).Select
With Selection.Format.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(0, 176, 80)
    .Transparency = 0
End With
End Sub

我尝试多次重新创建这个宏来根据我的需要进行塑造,所以我运行了一次测试它,一旦它到达With Selection.Format.Linegiving me this error就会破坏。宏的哪一部分导致了这个错误?

编辑:Shai Rado发布了完美修复Recorded macro breaks on Legend formatting

1 个答案:

答案 0 :(得分:1)

下面的代码将“图表19”的ChartObject设置为变量,稍后只需修改所需的参数,而无需使用ActiveChartSelectionSelect

Option Explicit

Sub Total()

Dim ChtObj As ChartObject

Set ChtObj = Worksheets("Sheet4").ChartObjects("Chart 19") '<-- modify "Sheet4" to your sheet's name where you have your charts

With ChtObj
    With .Chart.SeriesCollection(1).Format.Line
        .Visible = msoTrue
        .ForeColor.ObjectThemeColor = msoThemeColorText1
        .Transparency = 0
    End With

    With .Chart.SeriesCollection(5).Format.Line
        .Visible = msoTrue
        .ForeColor.RGB = RGB(255, 255, 0)
        .Transparency = 0
    End With

    With .Chart.SeriesCollection(6).Format.Line
       .Visible = msoTrue
        .ForeColor.RGB = RGB(0, 176, 80)
        .Transparency = 0
    End With            
End With

End Sub