VBA代码仅适用于某些图表

时间:2016-08-23 19:40:22

标签: excel vba excel-vba

我在工作表的所有图表上更新辅助轴范围的VBA代码仅适用于某些图表。宏运行后,消息"方法'轴'对象' _Chart'失败"显示,该工作表上只有一些图表正在更新。这里的问题是什么?

Sub Macro1()

Dim objChart As ChartObject, lower As Double, upper As Double

lower = Application.InputBox(prompt:="Enter lower bound", Type:=1)
upper = Application.InputBox(prompt:="Enter upper bound", Type:=1)

For Each objChart In Sheets("Summary").ChartObjects
    With objChart.Chart.Axes(xlValue, xlSecondary)
        .MinimumScale = lower
        .MaximumScale = upper
    End With
Next objChart

End Sub

1 个答案:

答案 0 :(得分:0)

如果ChartObject没有辅助轴,则访问它会引发错误。我无法找到一种方法来重现您的确切错误,但正如我在a comment中所说的,提取过程和处理运行时错误至少应该有助于诊断问题并使循环迭代所有图表:< / p>

Public Sub UpdateSummarySheetChartAxes()

    Dim lower As Double
    lower = Application.InputBox(prompt:="Enter lower bound", Type:=1)

    Dim upper As Double        
    upper = Application.InputBox(prompt:="Enter upper bound", Type:=1)

    Dim objChart As ChartObject
    For Each objChart In Sheets("Summary").ChartObjects
        UpdateChartAxes objChart, lower, upper
    Next objChart

End Sub

Private Sub UpdateChartAxes(ByVal objChart As ChartObject, ByVal lower As Double, ByVal upper As Double)
    On Error GoTo CleanFail
    With objChart.Chart.Axes(xlValue, xlSecondary)
        .MinimumScale = lower
        .MaximumScale = upper
    End With
CleanExit:
    Exit Sub
CleanFail:
    Debug.Print "Failed updating axes for chart '" & objChart.Name & "'. Message: " & Err.Description
    Resume CleanExit
End Sub