从 ChartObjects 获取图表标题

Get chart title from ChartObjects

我希望能够通过标题(或我给它起的其他 non-default 名称)来识别图表。如果它有特定的标题,我在这里尝试删除它:

Sub delchart()

Call create_chart
Dim d

For Each d In Worksheets("sheet1").ChartObjects

    Debug.Print d.Name '<-not a usable name

    If d.ChartTitle = "Scatter Chart" Then '<- errors
        d.Delete
    End If
Next d
End Sub

以下是我创建图表的方式:

Sub create_chart()


    Dim sh As Worksheet
    Dim chrt As Chart

    Set sh = ActiveWorkbook.Worksheets("Sheet1")
    Set chrt = sh.Shapes.AddChart.Chart
    With chrt
        'Data?
        .ChartType = xlXYScatter
        .SeriesCollection.NewSeries
        .SeriesCollection(1).Name = "=""Scatter Chart"""
        .SeriesCollection(1).XValues = "=Sheet1!$A:$A"
        .SeriesCollection(1).Values = "=Sheet1!$B:$B"

        'Titles
        .HasTitle = True
        .ChartTitle.Characters.Text = "Scatter Chart"
        .Axes(xlCategory, xlPrimary).HasTitle = True
        .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "X values"
        .Axes(xlValue, xlPrimary).HasTitle = True
        .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Y values"
        .Axes(xlCategory).HasMajorGridlines = True

        'Formatting
        .Axes(xlCategory).HasMinorGridlines = False
        .Axes(xlValue).HasMajorGridlines = True
        .Axes(xlValue).HasMinorGridlines = False
        .HasLegend = False
        .Location Where:=xlLocationAsObject, Name:="Sheet1"
        '.Name = "my scatter 1"
    End With

End Sub

如果图表有我给它的特定标识,我该如何删除它?图表标题对我来说是最直观的,但似乎无法通过 ChartObject 访问标题。

您可以像这样访问 ChartTitle 文本:

Sub delchart()

Call create_chart
Dim d

For Each d In Worksheets("sheet1").ChartObjects

    Debug.Print d.Name '<-not a usable name

    If d.Chart.ChartTitle.Caption = "Scatter Chart" Then
        d.Delete
    End If
Next d

End Sub