2017-03-03 75 views
0

我試圖使用Sheet1中的值更新不同圖紙(圖表2)中圖表的最大比例和最小比例。但是我得到對象所需的錯誤。以下是代碼:Excel VBA - 圖表參考不起作用

Sub ChangeAxisScale() 
Dim wsChart As Chart 
Dim wsInput As Worksheet 
Dim LastRow As Long 


Set wsInput = ThisWorkbook.Sheets("Sheet1") 

With Sheet2.ChartObjects("Chart").Chart.Axes(xlValue) 
     LastRow = wsInput.Cells(wsInput.Rows.Count, "D").End(xlUp).Row 
     .MaximumScale = wsInput.Cells(LastRow, 4).Value 
     .MinimumScale = wsInput.Range("D2").Value 
End With 
End Sub 

出現錯誤的行是With Sheet2.ChartObjects("Chart").Chart.Axes(xlValue)。我錯誤地引用了圖表嗎?

謝謝。

回答

0

如果圖表位於內部名稱爲「Sheet2」的工作表上,那麼您的代碼運行良好。如果圖表位於不同名稱的工作表上,則代碼將失敗。

您可能希望使用Dim語句來聲明並正確設置圖表所在的工作表。

Sub ChangeAxisScale() 
Dim wsChart As Chart ' you don't really need that, right? 
Dim wsInput As Worksheet, wsChartSheet As Worksheet 
Dim LastRow As Long 


Set wsInput = ThisWorkbook.Sheets("Sheet1") 
Set wsChartSheet = ThisWorkbook.Sheets("Sheet2") 

With wsChartSheet.ChartObjects("Chart").Chart.Axes(xlValue) 
     LastRow = wsInput.Cells(wsInput.Rows.Count, "D").End(xlUp).Row 
     .MaximumScale = wsInput.Cells(LastRow, 4).Value 
     .MinimumScale = wsInput.Range("D2").Value 
End With 
End Sub