首页 > 解决方案 > 从特定列数据读取的 VBA 代码

问题描述

此 VBA 代码自动创建 PT 和图表。

我希望我的图表从“总计”列中读取。它默认并从第一列“关闭”中读取。

下面是我的代码:

Sub PT_C_RiskType_Status_test()
'
' PT_C_RiskType_Status_test Macro
'


    'Defining the variables

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


    Set pc = ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:="DataSource", _
    Version:=xlPivotTableVersion15)


    Set ws = Sheets.Add

    ws.Select
    Cells(3, 1).Select
    Range("A3:D9").Select


     'Create the pivot table

    Set pt = pc.CreatePivotTable(TableDestination:=ws.Name & "!R3C1", _
                                TableName:="Pivottable")


     'Adding the data fields

    pt.AddDataField _
        Field:=pt.PivotFields("Status"), _
        Function:=XlConsolidationFunction.xlCount

     'Adding the fields


        pt.AddFields _
        RowFields:="Risk Type", _
        ColumnFields:="Status"


    'Adding chart

    Set sh = ws.Shapes.AddChart2(XlChartType:=XlChartType.xlPie, _
                Width:=200, Height:=200)


    Set ch = sh.Chart

End Sub

请指教。

标签: excelvba

解决方案


推荐阅读