2014-06-18 59 views
1

我有一些使用命名範圍創建動態圖表的代碼。圖表應該只有5個系列,但由於某種原因,它創造的不止於此。因此,我想確定該圖表有多少個系列,並刪除SeriesCollection(5)上的所有系列。我相信我這樣做的方式效率很低,並且已經分解了好幾次(由於無效參數錯誤)。我如何以有效的方式編寫這個任務,而不需要處理錯誤?目前我使用的代碼是:這些行後VBA確定系列計數和刪除

With ActiveChart 
    If .SeriesCollection.Count = 6 Then 
     .SeriesCollection(6).Delete 
    End If 
    If .SeriesCollection.Count = 7 Then 
     .SeriesCollection(6).Delete 
     .SeriesCollection(7).Delete 
    End If 
    If .SeriesCollection.Count = 8 Then 
     .SeriesCollection(6).Delete 
     .SeriesCollection(7).Delete 
     .SeriesCollection(8).Delete 
    End If 
End With 
+1

最好的解決方案是真正弄清楚爲什麼你得到太多的系列並沒有在第一時間進行添加。 – CodeJockey

+0

我同意,雖然說起來容易做起來難! –

回答

2

展望:

If .SeriesCollection.Count = 7 Then 

您刪除SeriesCollection(6)它執行罰款。但是,收藏品的工作方式是順序的,所以SeriesCollection(7)被下移到(6)的位置。然後,當你去刪除(7)它不再存在,你會得到一個錯誤。試試這個:

If .SeriesCollection.Count = 7 Then 

    .SeriesCollection(7).Delete 

    .SeriesCollection(6).Delete 

End If 

If .SeriesCollection.Count = 8 Then 

    .SeriesCollection(8).Delete 

    .SeriesCollection(7).Delete 

    .SeriesCollection(6).Delete 

End If 

讓我們知道這是否有效。

2

下面是另一種方式,最終將歸結爲更少的代碼行,而不必擔心必須添加一堆if語句來解決「最糟糕的情況」。此外,如果您有少於6個系列,它會在刪除跳過所有在一起:

Sub test() 
Dim seriesCount As Long 
Dim counter As Long 

With ActiveChart 
    seriesCount = .SeriesCollection.Count 

    For counter = seriesCount To 6 Step -1 
     .SeriesCollection(counter).Delete 
    Next counter 
End With 
End Sub 

而作爲CodeJockey指出out..when刪除,總是從下往上走(保持方便的信息,該位當你想循環遍歷行並刪除它們時)。

0

我認爲這裏理解的關鍵點是,您的圖表系列清單在每次刪除系列時重新編號爲連續1 ... N。所以如果你有8個系列,你有系列指數1 ... 8。如果您刪除了seriesCollection(6),現在您的系列編號爲1 ... 7。但是請注意,你仍然有一個系列集合(6) - 這是在刪除步驟之前的第7個系列。

這裏是我的代碼的建議:

Do While .SeriesCollection.Count > 5 
    .SeriesCollection(6).Delete 
Loop