Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

My Pivot Table Code is generating a PivotField property error

Status
Not open for further replies.

susu

Technical User
May 15, 2001
5
US
Hello Everyone,
I wrote this VB code in within Excel to generate Pivot Tables, I have different Excel Geography files, For example, County, or State or WIA files. so I used select..case statement for the variable "strArea". Also, I wanted to select a certain field to be the default DataField in the Pivot table, so I decalsred it as "strVar". But I keep getting a run-time error "Unable to get the PivotFields property of the Pivot Table class". I can not figure it out. Can anyone help with this problem.
Thank you


Sub CreatePivotTable()
Dim ptcache As PivotCache
Dim pt As PivotTable
Dim strArea As String
Dim strVar As String
Dim i As Integer

Set ptcache = ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlDatabase, _
SourceData:=Range("a1").CurrentRegion.Address)

Set pt = ptcache.CreatePivotTable _
(tabledestination:="", _
tablename:="pivottable1")

strArea = ActiveSheet.Cells(1, 1).Value

Select Case strArea
Case "county"
With pt
.PivotFields("county").Orientation = xlPageField
.PivotFields("sicdivfmt").Orientation = xlPageField
End With
Case "wib"
With pt
.PivotFields("wib").Orientation = xlPageField
.PivotFields("sicdivfmt").Orientation = xlPageField
End With
Case "State"
With pt
If i = 2 Then
.PivotFields("state").Orientation = xlPageField
.PivotFields("sic & 2 & fmt").Orientation = xlPageField
ElseIf i = 3 Then
.PivotFields("state").Orientation = xlPageField
.PivotFields("sic & 3 & fmt").Orientation = xlPageField
Else
.PivotFields("state").Orientation = xlPageField
.PivotFields("sic & 4 & fmt").Orientation = xlPageField
End If
End With
End Select

With pt
.PivotFields("year").Orientation = xlRowField
.PivotFields("quarter").Orientation = xlRowField
.PivotFields("sexfmt").Orientation = xlColumnField
.PivotFields("agegroupfm").Orientation = xlColumnField
End With

strVar = ActiveSheet.Cells(1, 7).Value

With pt.PivotFields("strVar")
.Orientation = xlDataField
.Caption = "sum of " & "strVar"
.Function = xlSum
End With

Charts.Add
ActiveChart.Location WHERE:=xlLocationAsNewSheet
ActiveChart.ChartType = xlLine

End Sub


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top