2017-08-09 130 views
2

已使用此blog将图表轴与单元格值关联。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 - 有什么想法?

回答

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 
+0

我需要改变图表对象,如果它是一个图表工作表? – tj123

+0

@ tj123你没有在你的文章中提到有关图表的任何事情,你写了_“不同工作表上的多个图表”_这是不同的 –