Excel图表轴比例

已经使用这个博客链接图表轴到单元格值。

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 – 任何想法?

尝试下面的代码,解释代码内的评论:

 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