0

I am writing a little macro in Excel 2010 to move the chart title of a pivot chart, and I can get it to work using a method that activates the chart and selects the chart's title. Here is that code

Private Sub Worksheet_Calculate()

    'On Error GoTo GetOut
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    ActiveSheet.ChartObjects("Chart 1").Activate
    If ActiveChart.HasTitle = True Then
    ActiveChart.ChartTitle.Select
            With Selection
                .Left = 311.982
                .Top = 9.559
            End With
    End If

GetOut:
    ActiveSheet.Range("M21").Select
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub

But I would like to avoid activating the object, so I wrote this

Private Sub Worksheet_Calculate()

Dim empChart As ChartObject

'On Error GoTo GetOut
Application.ScreenUpdating = False
Application.EnableEvents = False

Set empChart = ActiveSheet.ChartObjects("Chart 1")
If empChart.HasTitle = True Then
    With empChart.ChartTitle
        .Left = 311.982
        .Top = 9.559
    End With
End If

GetOut:
ActiveSheet.Range("M21").Select
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub

But this gives me runtime error 438: Object doesn't support this property or method. I can't figure out why for the life of me. I'm not very good so it is probably something silly, but any help would be much appreciated

4

1 回答 1

3

工作表ChartObject有一个子Chart对象:您可以使用(例如)直接访问它

Dim cht As Chart
Set cht = ActiveSheet.ChartObjects("Chart 1").Chart 

然后你可以cht直接操作而不是使用ActiveChart。

于 2013-06-06T23:02:31.550 回答