2016-08-25 64 views
2

我試圖根據每個特定圖表中所有系列(最多1個)的最大和最小值更新所有圖表的y軸。 (因此所有的圖表都會根據系列的不同進行更新)。我怎樣才能做到這一點?據我所知,沒有簡單的SeriesCollection(全部)選項,所以我試圖使用循環。歡迎任何更好的建議。VBA:根據系列集合自動調整所有y軸範圍

Public Sub UpdateChartAxes() 

Dim objChart As ChartObject 
For Each objChart In Sheets("Charts").ChartObjects 
    UpdateChartAxis objChart 
Next objChart 

End Sub 

Private Sub UpdateChartAxis(ByVal objChart As ChartObject) 
On Error GoTo CleanFail 

Dim lower As Double 
Dim upper As Double 
Dim srs As Series 

lower = 100 
upper = 0 

With objChart.Chart 
For Each srs In .SeriesCollection 
If Application.RoundDown(Application.Aggregate(15, 6, srs, 1), 0) < lower _ 
    Then lower = Application.RoundDown(Application.Aggregate(15, 6, srs, 1), 0) 

If Application.RoundUp(Application.Aggregate(14, 6, srs, 1), 0) > upper _ 
    Then upper = Application.RoundUp(Application.Aggregate(14, 6, srs, 1), 0) 
Next srs 

.Axes(xlValue).MinimumScale = lower 
.Axes(xlValue).MaximumScale = upper 
End With 

CleanExit: 
Exit Sub 

CleanFail: 
Debug.Print lower 
Debug.Print "Failed updating axes for chart '" & objChart.Name & "'.Message: " & Err.Description 
Resume CleanExit 
End Sub 
+0

您是否收到錯誤?你的代碼在哪一行跳轉到'CleanFail'? –

+0

你錯過了逗號,將你的'For Each srs In SeriesCollection'改爲'For Each srs In .SeriesCollection'(它與你的'With objChart.Chart'有關) –

+0

糟糕,這是一個錯字。在任何情況下,我都會收到所有圖表的錯誤「應用程序定義的或對象定義的錯誤」。 – rocketman

回答

0

問題是for循環中的「srs」(聚合不採用系列對象)。改爲使用「srs.Values」。