HiI have created a pivot table with the below code. However it does not include the second data field "Minutes" for some reason. All the fields are in range, when I switch them around and have "Minutes" first it includes it but not "TRUST No" vice versa. I don't know where I'm going wrong please help. Thank you in advance!
Code;
>>> use code - tags <<<
My goal is for the pivot table field to look like:
Code;
>>> use code - tags <<<
Code:
Sub CreatePivotTable()
Dim wb As Workbook
Dim dsheet As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable
Dim ptsheet As Worksheet
Dim lr As Long
Dim lc As Long
Dim prange As Range
Set wb = ActiveWorkbook
Set dsheet = ActiveSheet
`Check sheet name`
If Left(ActiveSheet.Name, 2) <> "EK" Then
MsgBox "This is not the active sheet, select EK daily tins ****** sheet and try again.", vbExclamation
Exit Sub
End If
`Find last row and column`
lr = dsheet.Cells(dsheet.Rows.Count, 1).End(xlUp).Row
lr = lr - 5 'Exclude first 4 and last rows of data'
lc = dsheet.Cells(5, dsheet.Columns.Count).End(xlToLeft).Column
`Set range to resize based on number of column and rows`
Set prange = dsheet.Cells(5, 1).Resize(lr, lc)
`Create new worksheet for pivot table`
Worksheets.Add after:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Set ptsheet = Worksheets("PivotTable")
`Create pivot cache and pivot table`
Set pc = wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=prange)
Set pt = pc.CreatePivotTable(TableDestination:=ptsheet.Range("A1"), TableName:="EK Tins")
`Add pivot fields`
With ptsheet.PivotTables("EK Tins").PivotFields("Resp Man")
.Orientation = xlRowField
End With
With ptsheet.PivotTables("EK Tins").PivotFields("TRUST No")
.Orientation = xlDataField
.PivotFields("TRUST No").Function = xlCount
.Position = 1
End With
With ptsheet.PivotTables("EK Tins").PivotFields("Minutes")
.Orientation = xlDataField
.PivotFields("Minutes").Function = xlSum
.Position = 2
End With
End Sub
Last edited by a moderator: