Excel VBA删除与宏的透视图

时间:2014-06-10 15:48:43

标签: excel vba excel-vba pivot

我的Excel工作表上有一个按钮,可以在单击时创建数据透视表和数据透视表。由于它将多次运行,每次运行时我都需要删除现有的表和图表。该表没有问题,但每次都会使用增量编号重命名图表。我需要知道运行中的图表名称才能删除它。

这是我创建的表格/图表:

   Sheets("EditListingCriteria").Select
    RowNumber = "R" & Application.CountA(Range("A:A")) & "C19"

    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    ActiveWorkbook.Worksheets("PivotTable").PivotTables("PivotTable5").PivotCache. _
        CreatePivotTable TableDestination:="Charts!R5C3", TableName:="PivotTable6" _
        , DefaultVersion:=xlPivotTableVersion14
    Sheets("Charts").Select
    Cells(5, 3).Select
    ActiveSheet.PivotTables("PivotTable6").AddDataField ActiveSheet.PivotTables( _
        "PivotTable6").PivotFields("Material Weight"), "Sum of Material Weight", xlSum
    With ActiveSheet.PivotTables("PivotTable6").PivotFields("Shipment Month")
        .Orientation = xlRowField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable6").PivotFields("Ordered Ship Mode")
        .Orientation = xlPageField
        .Position = 1
    End With
    With ActiveSheet.PivotTables("PivotTable6").PivotFields("Actual Ship Mode")
        .Orientation = xlColumnField
        .Position = 1
    End With
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xl3DColumnClustered
    ActiveChart.SetSourceData Source:=Range("Charts!$C$5:$F$12")
    'Rename chart here?
    Rows("2:12").RowHeight = 0
    Rows("1:1").RowHeight = 0

删除:

ActiveSheet.ChartObjects("Chart 10").Activate  
ActiveChart.Parent.delete

我尝试了以下命令重命名,但它总是打破

 chartname = ActiveChart.Name
ActiveSheet.Shapes(chartname).Name = "MonthlyChart"

1 个答案:

答案 0 :(得分:2)

试试这个:

'To create a chart
Dim S As Worksheet
Dim C As Chart

Set S = Activesheet
Set C = S.Shapes.AddChart.Chart
S.Shapes(C.Parent.Name).Name = "MonthlyChart"

'To delete the chart later in the same sub:
C.Parent.Delete

'Or if your delete code is in a different sub (I suspect it is):
Dim S As Worksheet
Set S = Activesheet

S.ChartObjects("MonthlyChart").Delete