2017-08-09 171 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你沒有在你的文章中提到有關圖表的任何事情,你寫了_「不同工作表上的多個圖表」_這是不同的 –