2015-07-21 51 views
3

我有一系列使用VBA創建的圖表(代碼如下)。如何更改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 
+0

沒有活躍的圖表。使用'Set Srs1 = .SeriesCollection(1)'等 –

回答

6

嘗試改變這些線...

 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" 

您已經使用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" 
+1

或者只是'設置Srs1 = .SeriesCollection(1)'等。 –