命名使用.shapes.chart创建的图表

时间:2019-03-14 10:22:38

标签: vba pivot

我一直在试图找出我在做错什么,但我找不到答案。我有以下代码:

Sub CreatePivotChart()

    Dim sh As Shape
    Dim ws As Worksheet
    Dim ch As Chart
    Dim pt As PivotTable

    DeleteAllChartObjects

    'setting ws and sh will be done alot here. It's basically making it easy for yourself by making a new (short name):
    Set ws = Worksheets("Analysis")
    Set sh = ws.Shapes.AddChart(XlChartType:=xlColumn, Width:=400, Height:=200)


    'This part to make sure that when there's no cell selected when running the code) within the pivottable, it still works
    Set ch = sh.Chart


    'Acipivot is created as title for the pivottable in sbCreativpivot:
    Set pt = Worksheets("PivotTable").PivotTables("Acpivot")
    ch.SetSourceData pt.TableRange1

    'align the chart with the table:
    sh.Top = pt.TableRange1.Top
    sh.Left = pt.TableRange1.Left + pt.TableRange1.Width + 10

End Sub

一切正常,除了我无法命名图表。我尝试了几种在网上找到的方法,但是似乎都没有用。

这是我最近的尝试:

'This part to make sure that when there's no cell selected when running the code) within the pivottable, it still works
Set ch = sh.Chart
With ch
    With .Parent.Name = "test"
    End With
End With

但是,如果我尝试像这里这样引用它:

Sub EditPivotChart()

    Dim pt As PivotTable
    Dim ch As Chart
    Dim pf As PivotField

    Set ch = Charts("test")
    Set pt = ch.PivotLayout.PivotTable

    For Each pf In pt.VisibleFields
        pf.Orientation = xlHidden
    Next pf

End Sub

我收到错误

  

vba内存不足

有人看到我在做什么错吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以删除以下所有细分

With ch
    With .Parent.Name = "test"
    End With
End With

,只需将其替换为

sh.Name = "test"

应该可以解决问题。