Excel图表轴刻度

时间:2017-08-09 07:23:12

标签: excel vba excel-vba charts

一直使用此blog将图表轴与单元格值相关联。

Sub ScaleAxes()

    Dim wks As Worksheet
    Set ws = Worksheets("AXIS")
    Set cht = ActiveWorkbook.ChartObjects("ChartName1","ChartName2")

    For Each cht In ActiveWorkbook.ChartObjects
        cht.Activate
        With ActiveChart.Axes(xlCategory, xlPrimary)
            .MaximumScale = ws.Range("$B$12").Value
            .MinimumScale = ws.Range("$B$11").Value
            .MajorUnit = ws.Range("$B$13").Value
        End With
    Next cht

End Sub

我的目标是使用轴值的单个工作表来更新不同工作表上的多个图表。大多数示例都在同一工作表上使用图表。我目前得到错误438 - 任何想法?

1 个答案:

答案 0 :(得分:0)

尝试下面的代码,代码中的解释为注释:

Option Explicit

Sub ScaleAxes()

    Dim Sht As Worksheet
    Dim ws As Worksheet
    Dim chtObj As ChartObject
    Dim ChtNames

    Set ws = Worksheets("AXIS")
    ' you need to get the names of the charts into an array, not ChartObjects array
    ChtNames = Array("ChartName1", "ChartName2")

    ' first loop through all worksheet
    For Each Sht In ActiveWorkbook.Worksheets
        ' loop through all ChartObjects in each worksheet
        For Each chtObj In Sht.ChartObjects
            With chtObj

                '=== use the Match function to check if current chart's name is found within the ChtNames array ===
                If Not IsError(Application.Match(.Name, ChtNames, 0)) Then
                    With .Chart.Axes(xlCategory, xlPrimary)
                        .MaximumScale = ws.Range("B12").Value
                        .MinimumScale = ws.Range("B11").Value
                        .MajorUnit = ws.Range("B13").Value
                    End With
                End If
            End With
        Next chtObj
    Next Sht

End Sub