I am working on a macro in which I am putting together PivotTables.
My Problem:
I can not get the calculation part to work. I get an error everytime I run the code at the stage where PivotField(18) is supposed to calculate the .Function=xlCount. The error I get is “1004 select method of range class failed”.
All the examples I’ve found online and in the MS Help section are structured the way I have set up my code. What am I missing???
Any help is highly appreciated…
I’ve been working on this the better part of the day. The following page (Link) has been super helpful, but hasn’t helped me in cracking this particular problem.
' Start of PivotSpecific Formatting
Set pt = ActiveSheet.PivotTables("PT" & wsNewWorksheetName)
With pt
' Prevent AutoFormatting of Columns
.HasAutoFormat = False
' Hide Field Headers
.DisplayFieldCaptions = False
.TableStyle2 = "PivotStyleMedium2"
' Apply calculation to numbers and change Caption
With .PivotFields(18)
.Caption = "Demand"
.Function = xlCount
.NumberFormat = "#,##0"
End With
With .PivotFields(15)
.Caption = "Lowest OP"
.Function = xlMin
.NumberFormat = "#,##0.00"
End With
End With
Update 1: Screenshot of Pivot Table

Update 2: Tested Code from bonCodigo
Here is the code adjusted to my workbook. With this I get a run time error 91 on the line:
Set pvField = pvTable.PivotFields(18)
Dim wkSheet As Worksheet
Dim pvTable As PivotTable
Dim pvField As PivotField
Set wkSheet = ThisWorkbook.Worksheets(wsNewWorksheetName)
Set pvTble = wkSheet.PivotTables("PT" & wsNewWorksheetName)
Set pvField = pvTable.PivotFields(18)
With pvField
.Caption = "Demand"
.Function = xlCount
.orientation = xlDataField
.NumberFormat = "#,##0"
End With
Set pvField = Nothing
Set pvTable = Nothing
Set wkSheet = Nothing
Try this please and comment with your results. So we can see from there.
Since you have more than one field to format, I recommend you to use a loop if they are consecutive using
DataFields Indexe.g.
pvTable.DataFields(1).Function = xlCountOtherwise you will have to define them separately. It is always best to assign an variable as a reference to the object that you intend to interact. 🙂