【问题标题】:How to change series name in VBA如何在 VBA 中更改系列名称
【发布时间】:2015-10-11 00:47:01
【问题描述】:

我有一系列使用 VBA 创建的图表(代码如下)。

我无法将系列名称从系列 1 和系列 2 更改为当前状态和解决方案状态。

我一直收到一个

对象变量或块变量未设置

错误。

但是,如果没有 srs1srs2 代码,图表就可以正常工作(只是使用了错误的系列名称)。

我查找了如何解决此问题,但我收到的答案对我不起作用。
有谁知道另一种方法来做到这一点?

Sub MA()
    Dim Srs1 As Series
    Dim Srs2 As Series
    Dim i  As Integer
    Dim MAChart As Chart
    Dim f As Integer
    f = 2 * Cells(2, 14)
     For i = 1 To f Step 2
        Set MAChart = ActiveSheet.Shapes.AddChart(Left:=750, Width:=400, Top:=130 + 50 * (i - 1), Height:=100).Chart
         With MAChart
         .PlotBy = xlRows
         .ChartType = xlColumnClustered
         .SetSourceData Source:=ActiveSheet.Range("Q" & 1 + i & ":Z" & 2 + i)
         .Axes(xlValue).MaximumScale = 4
         .Axes(xlValue).MinimumScale = 0
         .HasTitle = True
         .ChartTitle.Text = "Provider Load for " & Cells(i + 1, 15)
         'where errors start- works fine up to this point
         Set Srs1 = ActiveChart.SeriesCollection(1) 
         Srs1.Name = "Current State"
         Set Srs2 = ActiveChart.SeriesCollection(2) 
         Srs2.Name = "Proposed Solution"
         End With
    Next i
End Sub

【问题讨论】:

  • 没有活动图表。使用Set Srs1 = .SeriesCollection(1)

标签: vba excel charts series


【解决方案1】:

尝试更改这些行...

     Set Srs1 = ActiveChart.SeriesCollection(1) 
     Srs1.Name = "Current State"
     Set Srs2 = ActiveChart.SeriesCollection(2) 
     Srs2.Name = "Proposed Solution"

到...

     .SeriesCollection(1).Name = "Current State"
     .SeriesCollection(2).Name = "Proposed Solution"

您已经在 With 块中使用了 MAChart,因此您应该能够以与其他属性相同的方式访问它的 .SeriesCollection(x).Name 属性。

【讨论】:

    【解决方案2】:

    我认为问题在于引用 - 在您引用 ActiveChart 的代码中(我猜它不存在),而您在上面的代码中创建了 MAChart。

     Set Srs1 = MAChart.SeriesCollection(1) 
     Srs1.Name = "Current State"
     Set Srs2 = MAChart.SeriesCollection(2) 
     Srs2.Name = "Proposed Solution"
    

    【讨论】:

    • 或者只是Set Srs1 = .SeriesCollection(1)
    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2021-02-15
    • 2021-08-30
    • 2022-01-14
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多