Pivot Table VBA

chaddres

Board Regular
Joined
Jun 14, 2014
Messages
149
Office Version
  1. 365
Platform
  1. Windows
I have a macro that creates a pivot table and adds a filter called "PR Code". Everything works perfect, but is there a way to include the filter criteria in the VBA code? I only want to select PR Codes = 9J9 & 9AJ.

VBA Code:
'Overtime Check
    Sheets("Combined Time").Select
    Dim rng1 As Range
    Dim sht1 As Worksheet
    Dim pTable1 As PivotTable
    Set rng1 = ActiveSheet.Cells(1, 1).CurrentRegion
    Set sht1 = ActiveWorkbook.Worksheets.Add
    sht1.Name = "Overtime Pivot"
    Set pTable1 = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        rng1.Address, Version:=8).CreatePivotTable(TableDestination:= _
        sht1.Cells(1, 1), TableName:="PivotTable" & Format(Time, "hhmmss"))
    With pTable1
        With .PivotFields("DOB")
            .Orientation = xlPageField
        End With
        With .PivotFields("PR Code")
            .Orientation = xlPageField
        End With
        With .PivotFields("SSN")
            .Orientation = xlRowField
            .Subtotals(1) = False
        End With
        .PivotFields("Reg Hours").Orientation = xlDataField
    End With
    Columns("A:B").Select
    Selection.Copy
    Columns("D:E").Select
    ActiveSheet.Paste
End Sub
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
Try adding the following code in the .PivotFields("PR Code") section:
VBA Code:
Dim PI As PivotItem
    .EnableMultiplePageItems = True
        For Each PI In .PivotItems
            If PI = "9J9" Or PI = ")AJ" Then
                PI.Visible = True
            Else
                PI.Visible = False
            End If
        Next PI
 
Upvote 0
Solution

Forum statistics

Threads
1,223,871
Messages
6,175,092
Members
452,612
Latest member
MESTeacher

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top