如何在 VBA 中更改系列名称

How to change series name in VBA

我正在使用 VBA(下面的代码)创建一系列图表。

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

我一直收到

Object Variable or With Block Variable not set

错误。

然而,如果没有 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

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

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

尝试更改这些行...

     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 属性。