Excel VBA - 更新图表比例时出错

时间:2017-03-01 04:13:49

标签: excel vba excel-vba

我找到了一种更新图表的最大和最小比例的方法。我调整了代码以找到最后一行的最大比例值。以下是代码:

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

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

1 个答案:

答案 0 :(得分:0)

.Cells不是Axes类的属性,并且在您的With语句中,它会读取您要访问Axes的属性的时间,很可能是您正在尝试获取图表所在工作表的Cells属性。要获得对工作表的引用,您可以使用:

Dim ws As Worksheet

Set ws = ActiveChart.Parent.Parent

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

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