我有一系列使用VBA创建的图表(下面的代码)。
我无法将系列名称从系列1和系列2更改为当前状态和解决方案状态。
我一直在
对象变量或未设置块变量
错误。
但是,如果没有srs1
和srs2
代码,图表就可以正常运行(仅使用错误的系列名称)。
我查了解如何解决这个问题,但我收到的答案对我不起作用 有谁知道另一种方法吗?
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
答案 0 :(得分:8)
尝试更改这些行...
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
属性。
答案 1 :(得分:2)
我认为问题在于引用 - 在您引用ActiveChart的代码中(我猜它不存在),而您在上面的代码中创建了MAChart。
Set Srs1 = MAChart.SeriesCollection(1)
Srs1.Name = "Current State"
Set Srs2 = MAChart.SeriesCollection(2)
Srs2.Name = "Proposed Solution"