Name
pivotcaches
.Add(SourceType
, [SourceData
])
Synopsis
Creates a new pivot cache and returns a PivotCache
object.
Argument |
Settings |
---|---|
|
An |
|
If |
To create a pivot cache from a worksheet, use SourceType
xlDatabase
as shown here:
Sub CreateWSPivotTable( ) Dim pc As PivotCache, pt As PivotTable, rng As Range ' Create a new pivot cache (assumes active sheet is a worksheet). Set pc = ActiveWorkbook.PivotCaches.Add(xlDatabase, ActiveSheet.UsedRange) ' Create a pivot table. Set pt = pc.CreatePivotTable(Worksheets.Add( ).[a3]) ' Set the layout: add the column and row fields. pt.AddFields pt.PivotFields(4).Name, pt.PivotFields(3).Name ' Add the data field and set its formula. pt.AddDataField pt.PivotFields(1), , xlSum End Sub
To create a pivot cache from a database query, use SourceType
xlExternal
and then set the Connection
and CommandText
properties. The following code creates a pivot cache and pivot table from an SQL query to the Northwind SQL Server database:
Sub CreateNwindPivotCache( ) Dim pc As PivotCache, pt As PivotTable, rng As Range ' Create a new pivot cache. Set pc = ActiveWorkbook.PivotCaches.Add(xlExternal) ...
Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.