2017-03-03 60 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