Excel VBA – 更新图表比例中的错误

我find了一个方法来更新图表的最大和最小的规模。 我调整了代码,find最后一行的最大比例值。 以下是代码:

Sub ScaleAxes() Dim LastRow, LastRow2 As Long With ActiveChart.Axes(xlCategory, xlPrimary) LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row .MaximumScale = LastRow .MinimumScale = ActiveSheet.Range("A2").Value End With With ActiveChart.Axes(xlValue, xlPrimary) LastRow2 = .Cells(.Rows.Count, "B").End(xlUp).Row .MaximumScale = LastRow2 .MinimumScale = ActiveSheet.Range("B2").Value End With End Sub 

但是我得到“对象不支持此属性或方法”的错误。 林不知道哪部分我的代码是错误的。 希望你们能帮助我。

.Cells不是Axes类的一个属性,在你的With语句中,当你想要访问Axes属性的时候,它很可能是你试图获取图表所在的工作表的Cells属性。 要获得对工作表的参考,您可以使用:

 Dim ws As Worksheet Set ws = ActiveChart.Parent.Parent 

然后在获取LastRow值时使用ws引用:

 Option Explicit Sub ScaleAxes() Dim LastRow, LastRow2 As Long Dim ws As Worksheet Set ws = ActiveChart.Parent.Parent With ActiveChart.Axes(xlCategory, xlPrimary) LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row .MaximumScale = LastRow .MinimumScale = ActiveSheet.Range("A2").Value End With With ActiveChart.Axes(xlValue, xlPrimary) LastRow2 = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row .MaximumScale = LastRow2 .MinimumScale = ActiveSheet.Range("B2").Value End With End Sub