在与源数据(Excel VBA)相同的工作表中创建数据透视表

时间:2016-08-05 11:11:55

标签: excel vba excel-vba pivot pivot-table

我有一些数据是我使用以下VBA脚本构建的数据透视表的源。

代码正在创建一个新工作表并在那里生成数据透视表,但我希望数据透视表存在于源数据所在的同一工作表中。

还需要检查现有数据的位置,并且必须选择一个空单元格。

Sub ApplyPivot()

ActiveWorkbook.Sheets("NOIDA").Select
Range("A1").Select
Set objTable = Sheet1.PivotTableWizard

Set objField = objTable.PivotFields("sector")
objField.Orientation = xlRowField

Set objField = objTable.PivotFields("number")
objField.Orientation = xlColumnField

Set objField = objTable.PivotFields("quantity")
objField.Orientation = xlDataField
objField.Function = xlCount
objField.NumberFormat = " ######"

End Sub

1 个答案:

答案 0 :(得分:1)

以下是基于Range源数据在代码中创建数据透视表的一个非常基本的示例 - 它只是一些额外的行而不是每个使用向导你问题中的代码。

为了使表格远离源数据,它检查源数据中的列数,然后添加2列,即源数据和数据透视表之间将有一个空列。

Option Explicit

Sub ApplyPivotOnSameSheet()

    Dim wsTarget As Worksheet
    Dim rngData As Range
    Dim rngPivotTarget As Range
    Dim objCache As PivotCache
    Dim objTable As PivotTable
    Dim objField As PivotField

    'create pivot table in code (no wizard) on same sheet
    Set wsTarget = ThisWorkbook.Sheets("NOIDA")
    'set range to build table from
    Set rngData = wsTarget.Range("A1").CurrentRegion
    'set range for left-hand corner of pivot clear of source data by 1 column
    Set rngPivotTarget = wsTarget.Cells(1, rngData.Columns.Count + 2)
    'create cache from data
    Set objCache = ThisWorkbook.PivotCaches.Create(xlDatabase, rngData)
    'create table from cache
    Set objTable = objCache.CreatePivotTable(rngPivotTarget)

    'your original code
    Set objField = objTable.PivotFields("sector")
    objField.Orientation = xlRowField

    Set objField = objTable.PivotFields("number")
    objField.Orientation = xlColumnField

    Set objField = objTable.PivotFields("quantity")
    objField.Orientation = xlDataField
    objField.Function = xlCount
    objField.NumberFormat = " ######"

End Sub