jtvbs said:
I've tried recording a macro but that doesn't seem to translate into
vbscript. I think it has something to do with the wizard. Just
wondering if anyone has any experience with creating a Pivot Table
from within a vbscript.
Hi,
I struggled to do this, but found a way (see below).
Note that this may not work properly for you, and there is probably a
better way, but it may give you a starting point.
This is quite a dangerous area, since it guess it is possible for the
table to 'look' okay, but actually return incorrect results so I
suggest you test thoroughly before using it.
Any comments from others as to improvements are most welcome!
Alan.
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
NB: Exported is a worksheet already at this point
' Set the range to be pivoted to be called PivotRange
Set PivotTopLeft =
Exported.Parent.Worksheets("Sheet2").Range("A2")
Set PivotTopRight = PivotTopLeft.End(xlToRight)
Set PivotTop =
Exported.Parent.Worksheets("Sheet2").Range(PivotTopLeft,
PivotTopRight)
Set MyPivotRange =
Exported.Parent.Worksheets("Sheet2").Range(PivotTop,
PivotTop.End(xlDown))
' Create the pivot table
Application.CutCopyMode = False
Exported.Parent.Worksheets.Add
MyPivotRangeName = MyPivotRange.Parent.Name & "!" &
MyPivotRange.Address(ReferenceStyle:=xlR1C1)
Set MyPivotCache =
MyPivotRange.Parent.Parent.PivotCaches.Add(SourceType:=xlDatabase,
SourceData:=MyPivotRangeName)
MyPivotCache.CreatePivotTable
TableDestination:=Exported.Parent.Worksheets("Sheet3").Range("A1"), _
TableName:="PivotTable1"
Exported.Parent.Worksheets("Sheet3").PivotTables("PivotTable1").PivotT
ableWizard
Exported.Parent.Worksheets("Sheet3").PivotTables("PivotTable1").SmallG
rid = False
Exported.Parent.Worksheets("Sheet3").PivotTables("PivotTable1").AddFie
lds _
RowFields:="Type", _
ColumnFields:="Site Owner", _
PageFields:="Location"
With
Exported.Parent.Worksheets("Sheet3").PivotTables("PivotTable1"). _
PivotFields("Net Book Value" & Chr(10) & "($)")
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0"
End With