VBA Excel ERROR creating a second pivot table from the same database - excel

I'm not a rookie but not yet a pro on VBA Excel and I have encounter myself with a problem I have being struggling for a while.
Tried on google and this forum to read some data for a guide or the answer without success so I'll explain it to you hoping someone can give me a hint or enlightenment.
I want to code a VBA Macro that creates a Sheet from my Database called "ClientProperties" in which I'll create a Pivot Table "PT2" containing all the client names on a filtered state/Country and some properties like promotions name applied for that client, and the promotion value sorted by month. Then It will create a new sheet with the name of every state/Country on my Database but in each sheet I have to create one Pivot Table for each client ("PT1", "PT2", ... "PTn") showing the product categories that client has and sales sorted by month; Below that Pivot table I have to paste the properties from the "PT2" for that client.
I can create the "PT2", apply the filters and sort the information as needed without any problems but when I try to create the "PT1" it shows the error:
"Error '5' has occurred at runtime:
Invalid argument or procedure call".
The fist Pivot is actually created like this:
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "ClientProperties"
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Base!R1C1:R50C100"_
Version:=6).CreatePivotTable TableDestination:="ClientProperties!R3C1", TableName:="DT1", DefaultVersion:=6
The second (The one with error) like this (Note: PL(X) is an array of strings [state/Country name]):
For X = 0 To UBound(PL, 1)
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "" & PL(x) & ""
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Base!R1C1:R50C100"_
Version:=6).CreatePivotTable TableDestination:="" & PL(X) & "R8C23", TableName:="DT2", DefaultVersion:=6
Here is my code resumed:
Global LBD As Long, ABD As Integer, LBB As Long, ABB As Integer, PL(11) As String, CA() As String, AN As String, CTE As Boolean, TR As String * 1, FBB As Integer
Global ASS() As String, CAP() As String, FTD As Integer, ITD As Boolean, LTD As Integer, PN As String * 1, CRK As Integer, CANCEL As Boolean
Sub Main()
Call Variables
Worksheets("Base").Visible = True
Worksheets("Base").Select
LBD = Rows(1, 1)
ABD = Columns(1, 1)
Call AditionalProcess
Call ClientProps
Call SummaryTabs
Worksheets("Base").Visible = False
Worksheets("ClientProperties").Visible = False
End Sub
The Other modules are:
Sub Variables()
If TR = "M" Then
CTE = True
ReDim CA(3) As String
CA(0) = "Club"
CA(1) = "Conv"
CA(2) = "Reg"
CA(3) = "Ret"
Else
CTE = False
ReDim CA(3) As String
CA(0) = "Whs"
CA(1) = "C3"
CA(2) = "C5"
CA(3) = "Dist"
End If
PL(0) = "CALIFORNIA"
PL(1) = "FLORIDA"
If TR = "M" Then PL(2) = "AUSTIN" Else PL(2) = "HOUSTON"
PL(3) = "HAWAI"
PL(4) = "NEW JERSEY"
PL(5) = "ARIZONA"
PL(6) = "PENSILVANIA"
PL(7) = "VIRGINIA"
PL(8) = "MICHIGAN"
PL(9) = "GEORGIA"
PL(10) = "COLORADO"
PL(11) = "OHIO"
End Sub
Function Rows(X As Long, Y As Integer) As Long
Do While Cells(X, Y) <> Empty
X = X + 1
Loop
Rows = X - 1
End Function
Function Columns(X As Long, Y As Integer) As Long
Do While Cells(X, Y) <> Empty
Y = Y + 1
Loop
Columns = Y - 1
End Function
Sub AditionalProcess()
Worksheets("Base").Select
Range(Cells(2, 8), Cells(LBD, 8)).Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Paste
Application.CutCopyMode = False
Columns("A:A").RemoveDuplicates Columns:=1, Header:=xlNo
ReDim CAP(20) As String
For Y = 1 To 20
CAP(Y - 1) = Range(Cells(Y, 1), Cells(Y, 1))
Next Y
Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
End Sub
Sub ClientProps()
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "ClientProperties"
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Base!R1C1:R" & LBD & "C" & ABD & "", Version:=6).CreatePivotTable TableDestination:="ClientProperties!R3C1", TableName:="PT2", DefaultVersion:=6
Sheets("BB´s").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PT2")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
.PageFieldOrder = xlDownThenOver
End With
With ActiveSheet.PivotTables("PT2").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PT2").RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PT2").PivotFields("FY")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PT2").PivotFields("Client")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PT2")
.ColumnGrand = False
.RowGrand = False
End With
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M01"), " M01", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M02"), " M02", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M03"), " M03", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M04"), " M04", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M05"), " M05", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M06"), " M06", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M07"), " M07", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M08"), " M08", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M09"), " M09", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M10"), " M10", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M11"), " M11", xlSum
ActiveSheet.PivotTables("PT2").AddDataField ActiveSheet.PivotTables("PT2").PivotFields("M12"), " M12", xlSum
With ActiveSheet.PivotTables("PT2").PivotFields("PROMOS")
.Orientation = xlRowField
.Position = 1
End With
LBB = Rows(8, 1)
ABB = Columns(7, 1)
Range(Cells(8, 2), Cells(LBB, ABB)).Style = "Comma"
Range(Cells(8, 2), Cells(LBB, ABB)).NumberFormat = "_-* #,##0_-;-* #,##0_-;_-* ""-""??_-;_-#_-"
ActiveSheet.PivotTables("PT2").PivotFields("PROMOS").Subtotals = Array(False, False, False, False, False, False, False, False, False, False, False, False)
ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
Sub SummaryTabs()
For X = 0 To UBound(PL, 1)
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "" & PL(X) & ""
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Base!R1C1:R" & LBD & "C" & ABD & "", Version:=6).CreatePivotTable TableDestination:="" & PL(X) & "!R8C23", TableName:="PT1." & (X+2), DefaultVersion:=6
End Sub
At this point is where the error message appears and that's why i cut the code...

Two things:
you are missing '!' before the range in loop (!R8C23 instead of R8C23)
PivotTable name is the same in the loop, that will not work
Also you can use the same PivotCache for all the pivots, as it's always the same, like here (this code has both issues fixed):
Dim ws As Worksheet
Set ws = Sheets.Add(After:=ActiveSheet)
ws.Name = "ClientProperties"
Dim pc as PivotCache
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Base!R1C1:R50C100", _
Version:=6)
pc.CreatePivotTable TableDestination:="ClientProperties!R3C1", TableName:="DT1", DefaultVersion:=6
For X = 0 To UBound(PL, 1)
Set ws = Sheets.Add(After:=ActiveSheet)
ws.Name = "" & PL(x) & ""
pc.CreatePivotTable TableDestination:="" & PL(X) & "!R8C23", TableName:="DT" & (X+2), DefaultVersion:=6

I Just found the answer:
The sheet name in:
TableDestination:="" & PL(X) & "!R8C23"
needs to be surrounded with single quotes in order for it to work:
TableDestination:="'" & PL(X) & "'!R8C23"
Thank you all for your support!!!

Related

Creating multiple pivot tables using Excel VBA - each pivot table filtered with a distinct value

I have done some searching and can't find any posts with similar issue. I want to create 3 pivot tables on a new sheet, with each table filtered by column B as shown below. The number of items in column B may increase/decrease. I need the macro to loop through all the different combinations of items and apply this filter to each pivot table created.
I have very limited experience with loops in VBA so don't even know where to start.
I have attached screenshots below of the required solution + the code VBA generates for creating a pivot table from a sample table I've created.
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+a
'
Range("A1").Select
Application.CutCopyMode = False
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$C$5"), , xlYes).Name = _
"Table1"
Range("Table1[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight1"
Application.CutCopyMode = False
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table1", Version:=7).CreatePivotTable TableDestination:="Sheet2!R3C1", _
TableName:="PivotTable1", DefaultVersion:=7
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1")
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable1").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable1").RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Category")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Traffic"), "Sum of Traffic", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"Assign a unique number to a value")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"Assign a unique number to a value").ClearAllFilters
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"Assign a unique number to a value").CurrentPage = "1"
End Sub
Also enclosing the sample data screenshot. Thanks in advance guys!
EDIT: Pictures didn't upload so trying to upload again now.
macro_test_data
macro_test_pivot_table

VBA | Export To Multi-Page PDF

So I have a worksheet with a landscape orientation that I am exporting to a PDF. I can achieve this without any issues by selecting the usedRange of the activesheet, but the content prints to just one page, even if the used range is outside of the print area. How might I go about getting it to print a multi-page PDF in this case? My code is below:
Dim numSheets As Integer
numSheets = UBound(SlotArray)
For z = LBound(SlotArray) To UBound(SlotArray)
Set attendSh = ThisWorkbook.Sheets(SlotArray(z))
attendSh.Activate
ThisWorkbook.ActiveSheet.UsedRange.Select
Next z
Select Case numSheets
Case "0"
ThisWorkbook.Sheets(Array(SlotArray(0))).Select
Case "1"
ThisWorkbook.Sheets(Array(SlotArray(0), SlotArray(1))).Select
Case "2"
ThisWorkbook.Sheets(Array(SlotArray(0), SlotArray(1), SlotArray(2))).Select
Case "3"
ThisWorkbook.Sheets(Array(SlotArray(0), SlotArray(1), SlotArray(2), SlotArray(3))).Select
Case "4"
ThisWorkbook.Sheets(Array(SlotArray(0), SlotArray(1), SlotArray(2), SlotArray(3), SlotArray(4))).Select
Case "5"
ThisWorkbook.Sheets(Array(SlotArray(0), SlotArray(1), SlotArray(2), SlotArray(3), SlotArray(4), SlotArray(5))).Select
Case "6"
ThisWorkbook.Sheets(Array(SlotArray(0), SlotArray(1), SlotArray(2), SlotArray(3), SlotArray(4), SlotArray(5), SlotArray(6))).Select
End Select
Application.PrintCommunication = False
With ThisWorkbook.ActiveSheet.PageSetup
.Orientation = xlLandscape
.CenterHorizontally = True
'.Zoom = 90
.FitToPagesWide = 1
.FitToPagesTall = 1
.PrintComments = False
.PrintGridlines = False
End With
Application.PrintCommunication = True
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
FilePath & "\" & Year & " Monthly Attendance\" & "\" & Year & " " & Month & " Attendance.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False
where slotArray is an array of sheet names.
Try applying the PageSetUp to every sheet in the array.
Dim numSheets As Long, Z As Long
numSheets = UBound(SlotArray)
Dim ws As Worksheet
For Z = LBound(SlotArray) To UBound(SlotArray)
Set ws = ThisWorkbook.Sheets(SlotArray(Z))
With ws.PageSetup
.Orientation = xlLandscape
.CenterHorizontally = True
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintComments = xlPrintNoComments
.PrintGridlines = False
.PrintArea = ws.UsedRange.Address
End With
Next Z
ThisWorkbook.Sheets(SlotArray).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="Attendance.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
MsgBox "Printed " & vbLf & Join(SlotArray, vbLf)

pivot table creation on different sheets fails on second sheet

I am new in VBA programming and this is one my first codes i am writing.
Purpose of code: I'd like to take data on Invoices sheet and take it apart to different sheets based on the last column. Then on each sheet create a pivot table for the data.
The code is quite long - i am sure there are quite a lot of unnecessary steps in it but it is 90% ok.
The frist sheet is created perfectly. The first pivot is also created. Then the second sheet is also created.
Problem: The macro runs on an error when it tries to create the pivot table for the second sheet.
Error message: Run-time error'5': Invalid Procedure call or argument
Does anyone have an idea why my macro fails on the second sheet? Thank You for your help!
Pleaase see the code below. The problem occurs after the comment of creating a pivot table
Sub copypaste()
Application.ScreenUpdating = False
'Declarations
Dim ws As Worksheet
Dim wb As Workbook
Dim cell As Range
Dim rng As Range
Dim rng1 As Range
Dim ws2 As Worksheet
Dim ws3 As Worksheet
Dim LastRow As Long
Dim LastRow2 As Long
Dim Counter As Integer
Set wb = ActiveWorkbook
Set ws2 = wb.Sheets("Invoices")
Counter = 0
Debug.Print Counter
'get the number of rows in the invoices sheet
LastRow = ws2.Range("A1", ws2.Range("A1").End(xlDown)).Rows.Count
'plus invoice type and sum column creation
ws2.Select
Columns(6).Select
Range("F:F").Insert
Cells(1, 6) = "Invoice type"
Range("F2:F" & LastRow).Formula = "=LEFT(RC[1],4)"
Selection.Columns.AutoFit
Columns(19).Select
Range("S:S").Insert
Cells(1, 19) = "Sum"
Range("S2:S" & LastRow).Formula = "=SUM(RC[-8]:RC[-1])"
Selection.Style = "Comma"
Selection.NumberFormat = _
"_-* #,##0.0 _F_t_-;-* #,##0.0 _F_t_-;_-* ""-""?? _F_t_-;_-#_-"
Selection.NumberFormat = _
"_-* #,##0 _F_t_-;-* #,##0 _F_t_-;_-* ""-""?? _F_t_-;_-#_-"
Selection.Columns.AutoFit
'sorbarendezés debtor name és invoice no. szerint
ws2.Sort.SortFields.Clear
Range("A1:R" & LastRow).Sort Key1:=Range("E1"), Header:=xlYes, Key2:=Range("G1")
'list creation as a basis for filtering and taking apart the data
wb.Activate
ws2.Select
Range("A1").Select
Selection.End(xlToRight).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Set ws3 = Sheets.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveSheet.Range(Selection, Selection.End(xlDown)).RemoveDuplicates Columns:=1, Header:= _
xlYes
Range("A2").Select
Set rng1 = Range(Selection, Selection.End(xlDown))
ws3.Select
ws3.Name = "kódolás"
Set ws = wb.Sheets("kódolás")
wb.Activate
ws.Select
'go through the earlier created list and take apart the data related to each item of the list to separate sheets
For Each cell In rng1
Counter = Counter + 1
Debug.Print Counter
'filtered data copy
ws2.Select
Range("A1").Select
ws2.Range("$A$1:$W$198162").AutoFilter Field:=20, Criteria1:=cell
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'new sheet creation
With wb
.Sheets.Add after:=.Sheets(.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = cell.Value
If Err.Number = 1004 Then
Debug.Print cell.Value & " already used as a sheet name"
End If
On Error GoTo 0
End With
'filtered data paste
ActiveSheet.Paste
ActiveCell.Rows("1:1").EntireRow.Select
Application.CutCopyMode = False
'go back to A1
Range("A1").Select
'Creation of pivot table
LastRow2 = ActiveSheet.Range("A1", ActiveSheet.Range("A1").End(xlDown)).Rows.Count
ActiveCell.Range("A1:T" & LastRow2).Select
Debug.Print Counter
Debug.Print LastRow2
Debug.Print ActiveSheet.Name & "!" & "R1C1:R" & LastRow2 & "C19"
Debug.Print ActiveSheet.Name & "!" & "R1C23"
Debug.Print "PivotTable" & Counter
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
ActiveSheet.Name & "!" & "R1C1:R" & LastRow2 & "C19", Version:=6).CreatePivotTable TableDestination:= _
ActiveSheet.Name & "!" & "R1C23", TableName:="PivotTable" & Counter, DefaultVersion:=6
ActiveSheet.Select
Cells(1, 27).Select
With ActiveSheet.PivotTables("PivotTable" & Counter)
.ColumnGrand = True
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = True
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 1
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlCompactRow
End With
With ActiveSheet.PivotTables("PivotTable" & Counter).PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable" & Counter).RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable" & Counter).PivotFields("Debtor name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable" & Counter).PivotFields("invoice type")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable" & Counter).AddDataField ActiveSheet.PivotTables( _
"PivotTable" & Counter).PivotFields("SUM"), "Sum of SUM", xlSum
'take out filter and go back to A1
ws2.Select
Application.CutCopyMode = False
Range("A1").Select
ws2.AutoFilter.Sort.SortFields.Clear
ActiveSheet.ShowAllData
Next cell
End Sub

How do I position my pivot table filters above each other using VBA?

Basically, I have multiple tabs I am putting together, each with multiple pivots, where each pivot has multiple filters built in. These need to be visible to confirm the data you are seeing, since non-developers wouldn't know, how to access or understand VBA code.
What I want: Pivot table filters to be over each other in a list form:
What I currently get:
Here is a simplified version of the code...please let me know if there is a better way of doing this!
I tried using the Record Macro button in excel and format everything as I wanted to see, but once I actually run the macro, the filters are side by side rather than on top of each other.
Sub Macro5()
Columns("A:A").Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Dim dataname As String
Dim datasheetname As String
Dim pivotsheetname As String
dataname = ActiveSheet.ListObjects(1).Name
datasheetname = ActiveSheet.Name
pivotsheetname = datasheetname & " Pivot"
Sheets.Add
ActiveSheet.Name = pivotsheetname
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
dataname, Version:=6).CreatePivotTable TableDestination:= _
"'" & pivotsheetname & "'!R3C1", TableName:="PivotTable15",
DefaultVersion:=6
Sheets(pivotsheetname).Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable15")
.ColumnGrand = False
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = 2
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = False
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 3
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlTabularRow
End With
With ActiveSheet.PivotTables("PivotTable15").PivotCache
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault
End With
ActiveSheet.PivotTables("PivotTable15").RepeatAllLabels xlRepeatLabels
With ActiveSheet.PivotTables("PivotTable15").PivotFields("Billable?")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable15").PivotFields("Billed")
.Orientation = xlPageField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable15").PivotFields("Amount")
enter code here .Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable15").AddDataField
ActiveSheet.PivotTables( _
"PivotTable15").PivotFields("Qty"), "Sum of Qty", xlSum
End Sub
The order of the filter fields is defined by the parameter PageFieldOrder, which can be:
xlOverThenDown (= 2, your previous result)
xlDownThenOver (= 1, your desired result)
I optimized your code additionally:
normally, it i not necessary to select or activate anything
I added two variables to reference the pivotcache and the pivottable objects
the datafield can be added similar to the other pivotfields, but their name has to be set afterwards
Sub GenerateNewPivottable()
Dim datasheetname As String
Dim dataname As String
Dim pivotsheetname As String
Dim pc As PivotCache
Dim pt As PivotTable
Application.CutCopyMode = False
dataname = ActiveSheet.ListObjects(1).Name
datasheetname = ActiveSheet.Name
pivotsheetname = datasheetname & " Pivot"
Sheets.Add
ActiveSheet.Name = pivotsheetname
Set pc = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=dataname)
With pc
.RefreshOnFileOpen = False
.MissingItemsLimit = xlMissingItemsDefault ' better: xlMissingItemsNone
End With
Set pt = pc.CreatePivotTable( _
TableDestination:="'" & pivotsheetname & "'!R3C1", _
TableName:="PivotTable15")
With pt
.ColumnGrand = False
.HasAutoFormat = True
.DisplayErrorString = False
.DisplayNullString = True
.EnableDrilldown = True
.ErrorString = ""
.MergeLabels = False
.NullString = ""
.PageFieldOrder = XlOrder.xlDownThenOver
.PageFieldWrapCount = 0
.PreserveFormatting = True
.RowGrand = False
.SaveData = True
.PrintTitles = False
.RepeatItemsOnEachPrintedPage = True
.TotalsAnnotation = False
.CompactRowIndent = 3
.InGridDropZones = False
.DisplayFieldCaptions = True
.DisplayMemberPropertyTooltips = False
.DisplayContextTooltips = True
.ShowDrillIndicators = True
.PrintDrillIndicators = False
.AllowMultipleFilters = False
.SortUsingCustomLists = True
.FieldListSortAscending = False
.ShowValuesRow = False
.CalculatedMembersInFilters = False
.RowAxisLayout xlTabularRow
.RepeatAllLabels xlRepeatLabels
End With
With pt.PivotFields("Billable?")
.Orientation = xlPageField
.Position = 1
End With
With pt.PivotFields("Billed")
.Orientation = xlPageField
.Position = 1
End With
With pt.PivotFields("Amount")
.Orientation = xlPageField
.Position = 1
End With
With pt.PivotFields("Qty")
.Orientation = xlDataField
.Function = xlSum
.Name = "Sum of Qty"
End With
End Sub

VBA Macro Pivot Table Filter Error

In my spreadsheet, I have variable data; however, I have a specific set of attributes that I'd want to be filtered upon if/when they do appear in the data run for that week. If they do not appear, I'd like the Pivot Table filter to skip over it and continue to the next.
Unfortunately, I keep getting debugging errors when I try to run my macro. Can anyone help?
I.E.
If "1G1N13S2" isn't in the variable [raw] data, it'd carry me straight to the VBA to debug instead of skipping over it (whether false or true) to continue on to the subsequent ID#.
'PivotTable
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=ActiveSheet.UsedRange). _
CreatePivotTable TableDestination:="", TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion10
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
' BCA_Other Macro
With ActiveSheet.PivotTables("PivotTable1").PivotFields("ACTIVITY_ID")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("SUM_$"), "Count of SUM_$", xlCount
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Count of SUM_$")
.Caption = "Sum of SUM_$"
.Function = xlSum
.NumberFormat = "#,##0.00_);[Red](#,##0.00)"
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("WK_END_DATE")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("WK_END_DATE")
.PivotItems("(blank)").Visible = False
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("ANALYSIS_TYPE")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("ANALYSIS_TYPE"). _
CurrentPage = "ACT"
With ActiveSheet.PivotTables("PivotTable1").PivotFields("BUS_UNIT_GL_FROM")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("BUS_UNIT_GL_FROM"). _
CurrentPage = "AV"
'Activity ID Filter
With ActiveSheet.PivotTables("PivotTable1").PivotFields("ACTIVITY_ID")
.PivotItems("1G1N13S2").Visible = False
.PivotItems("1G1N2SAN").Visible = False
.PivotItems("1G1N5ACC").Visible = False
.PivotItems("1G1N5SCI").Visible = False
.PivotItems("1G1N5SDV").Visible = False
.PivotItems("1G1N5SMS").Visible = False
.PivotItems("1G1N5SST").Visible = False
.PivotItems("1G1N9BAT").Visible = False
.PivotItems("1G1N9EBT").Visible = False
.PivotItems("1G1N9EPL").Visible = False
.PivotItems("E6T66ZAV").Visible = True
.PivotItems("E6T66ZB3").Visible = True
.PivotItems("E6T66ZB4").Visible = True
.PivotItems("E6T66ZB5").Visible = True
.PivotItems("E6T66ZCU").Visible = True
.PivotItems("E6T66ZDX").Visible = True
.PivotItems("E6T66ZE9").Visible = True
.PivotItems("E6T66ZIL").Visible = True
.PivotItems("E6T66ZIS").Visible = True
.PivotItems("E6T66ZIV").Visible = True
.PivotItems("E6T66ZIZ").Visible = True
.PivotItems("E6T66ZJ6").Visible = True
.PivotItems("E6T66ZJ8").Visible = True
.PivotItems("E6T66ZJA").Visible = True
.PivotItems("EMAD0005").Visible = False
.PivotItems("EMADF006").Visible = False
.PivotItems("F8800YN5").Visible = True
.PivotItems("F8800YNU").Visible = True
.PivotItems("F8800YNW").Visible = True
.PivotItems("F8800YPM").Visible = True
End With
'Add new tabs for Hours and rename tabs to Dollars and Hours
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "BCA_Other_Dlrs"
Sheets("BCA_Other_Dlrs").Select
Sheets("BCA_Other_Dlrs").Copy Before:=Sheets(1)
Range("B18").Select
ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of SUM_$").Orientation _
= xlHidden
With ActiveSheet.PivotTables("PivotTable1").PivotFields("SUM_HOURS")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable1").PivotFields("SUM_HOURS").Orientation = _
xlHidden
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("SUM_HOURS"), "Count of SUM_HOURS", xlCount
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Count of SUM_HOURS")
.Caption = "Sum of SUM_HOURS"
.Function = xlSum
.NumberFormat = "#,##0.0_);[Red](#,##0.0)"
So, I've gotten an answer as to how to fix this.
On Error Resume Next
With ActiveSheet.PivotTables("PivotTable1").PivotFields("ACTIVITY_ID")
.PivotItems("1G1N13S2").Visible = False
.PivotItems("1G1N2SAN").Visible = False
.PivotItems("1G1N5ACC").Visible = False
.PivotItems("1G1N5SCI").Visible = False
.PivotItems("1G1N5SDV").Visible = False
.PivotItems("E6T66ZJA").Visible = True
End With
On Error Goto 0

Resources