So I am trying to create a pivot table. The code that I have now works fine. However, what I am trying to do now is create a new worksheet in my workbook and have the pivot table be made in the new worksheet. This code works fine when the worksheet is already there, however, once I add in the new line of code to create the new worksheet, it fails me.
Sub ISM_Pivot()
'-------------------------------------------------
' Step 1: Create a new worksheet for pivot table
'--------------------------------------------------
Dim WSD2 As Worksheet
Set WSD2 = ActiveWorkbook.Sheets.Add(After:= _
Worksheets(Worksheets.Count))
WSD2.Name = "POS Info"
'--------------------------------------------------
' Step 2: Create the pivot table
'--------------------------------------------------
Dim WSD As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PRange As Range
Dim FinalRow As Long
Dim FinalCol As Long
Dim StartPT As String
Set WSD = Worksheets("aggregateData")
' Select the data for pivot table
FinalRow = WSD.Cells(Rows.Count, 2).End(xlUp).Row
FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = WSD.Cells(2, 1).Resize(FinalRow, FinalCol)
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion14)
'Where do I want the pivot table to start
StartPT = WSD2.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Begin to Create the Pivot Table
Set PT = PTCache.CreatePivotTable(TableDestination:=StartPT, TableName:="POS Data")
The last line of code is where it fails me. I get an application defined or object-defined error.
Any help would be great,
Thanks,
Griffin
Related
I'm new here and a novice at VBA, so apologies in advance...
I'm trying to create a macro-button so that, when pressed, the Data Source for my Pivot Table (named 'Item Summary') is updated to a range of data that changes in size depending on the project, but will always be on a Worksheet called 'Usage' & the Pivot Table is on a worksheet named 'Item Summary' with data starting in cell A2.
The below works; however, it seems to be returning extra rows at the bottom resulting in a row of '(blank)' data on my Pivot Table -_- Any help would be much appreciated!
Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String
'Set Variables Equal to Data Sheet and Pivot Sheet
Set Data_sht = Worksheets("Usage")
Set Pivot_sht = Worksheets("Item Summary")
'Enter in Pivot Table Name
PivotName = "Item Summary"
'Dynamically Retrieve Range Address of Data
Set StartPoint = Data_sht.Range("A2")
Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))
NewRange = Data_sht.Name & "!" & _
DataRange.Address(ReferenceStyle:=xlR1C1)
I tried using the below edit in the 3rd to last line using a question/thread called, "Excel Pivot table range update via VBA gets too many rows"; however, I get a "Method 'Range' of object_Worksheet' failed." error :( Hopefully I'm just missing a tiny misspelled item, but I've been spinning my wheels here for a couple of hours now, so figured I'd see if anyone is able to assist.
Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String
Dim LastCol As Long
Dim DownCell As Long
'Set Variables Equal to Data Sheet and Pivot Sheet
Set Data_sht = Worksheets("Usage")
Set Pivot_sht = Worksheets("Item Summary")
'Enter in Pivot Table Name
PivotName = "Item Summary"
'Dynamically Retrieve Range Address of Data
Set StartPoint = Data_sht.Range("A2")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
**Set DataRange = Data_sht.Range(StartPoint, Cells(DownCell, LastCol))**
NewRange = Data_sht.Name & "!" & _
DataRange.Address(ReferenceStyle:=xlR1C1)
My objective is to filter a pivot table using a range in another sheet.
My pivot is in Worksheets("Aging Report").
My reference data using which I want to filter is in Columns A2 and onward in Worksheets("Instructions").
The below code worked on a table which did not have pivot table.
I need to take value from A2 then filter on ("Client ID") and export in Excel and save and so on with values in A3, A4, A5.
Sub Pivotfilter()
Dim varItemsToReplace As Variant
Dim varItem As Variant
Dim wksSource As Worksheet
Dim wksDest As Worksheet
Dim rngSource As Range
Dim rngSource2 As Range
Dim rngCell As Range
Set wksSource = Worksheets("Instructions")
Set wksDest = Worksheets("Aging Report")
With wksSource
Set rngSource = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
For Each rngCell In rngSource
With wksDest
ActiveSheet.PivotTables("PivotTable40").PivotFields ("Client ID")
.PivotFields(rngCell.Value).Visible = True
Dim wb As Workbook
Set wb = Workbooks.Add
Windows("XXXXXXX").Activate
Sheets("Aging Report").Select
Sheets("Aging Report").Copy Before:=wb.Sheets(1)
wb.SaveAs "C:\Users\XXX\Desktop\SOA\" & .Range("B3").Value & " - " & .Range("B4").Value & ".xlsx"
wb.Close
Windows("XXXXXXX.xlsm").Activate
End With
Next rngCell
End Sub
For filtering by value, my preferred method is to add more columns to the data itself, set the values by formulae, and add those columns to the pivot
Eg column Scope boolean added to pivot filter, filter on only true
Adding 30/60/90 aging column, add this to a pivot row to group by age
Etc
This lets you avoid needles complexity of combining two lesser known areas of expertise vba in general and vba specifically for pivots
Some Useful guidelines:
Raw Data:
Select the data and create a pivot table named "pvtTest" in Shhet 5
Try:
Option Explicit
Sub test()
Dim pvt As PivotTable
Dim Pf As PivotField
Dim strFilter As String
'Assign to variable "pvt" the pivot table to work with it
Set pvt = Worksheets("Sheet5").PivotTables("pvtTest")
'Assigh to "strFilter" the string to filter
strFilter = "A"
'Use column "Shop" as a filter of pivot table
pvt.PivotFields("Shop").Orientation = xlPageField
'Assign by which column the pivot table will be filtered
Set Pf = Worksheets("Sheet5").PivotTables("pvtTest").PivotFields("Shop")
'Clear filter previous choices
Pf.ClearAllFilters
'Select to filter the pivot table based on the value of "strFilter"
Pf.CurrentPage = strFilter
End Sub
VBA CODE:
I have a series of tables (one per sheet) that need to increase or decrease in size dynamically, based on number that has been input by a user (on another sheet).
Each row in each of the tables needs to maintain the formatting and formulas from the rows above, whilst being "inserted".
I have used the below to successfully increase the size of the table with the correct formatting, but this only adds rows to the table.. and if someone clicks the macro button multiple times we could end up with far too many rows. Hence why I would like a dynamic table where the rows are determined by a number and it wouldn't matter if someone was click happy.
I have also made another attempt which does increase the size of the table, but it doesn't insert additional rows, so the table overlaps data that is in rows below the determined table. This attempt does not copy the formatting either... but this is all i have so far. Any help would be much appreciated, I've been working on this for a couple of months and can't find a suitable answer (after days of searching).
Sub InsertNumberOfRows()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim NBOFROWS As Range
Dim wkb As Workbook
Set NBOFROWS = Worksheets("Rates").Range("K4")
Set wkb = Workbooks("POD Automation10.1")
With wkb
Set sh1 = ActiveWorkbook.Sheets("POD Cost Plan")
Set sh2 = ActiveWorkbook.Sheets("Development Calculator")
Set sh3 = ActiveWorkbook.Sheets("Calculator Calculations")
sh1.Select
Rows("10:10").Select
Selection.EntireRow.Offset(1).Resize(NBOFROWS.Value).Insert Shift:=xlDown,
CopyOrigin:=xlFormatFromLeftOrAbove
sh2.Select
Rows("10:10").Select
Selection.EntireRow.Offset(1).Resize(NBOFROWS.Value).Insert Shift:=xlDown,
CopyOrigin:=xlFormatFromLeftOrAbove
sh3.Select
Rows("10:10").Select
Selection.EntireRow.Offset(1).Resize(NBOFROWS.Value).Insert Shift:=xlDown,
CopyOrigin:=xlFormatFromLeftOrAbove
End With
End Sub
NEXT ATTEMPT:
Sub InsertNumberOfRows()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim Value As Range
Dim wkb As Workbook
Dim rng As Range
Dim tbl As ListObject
Set Value = Worksheets("Rates").Range("K4")
Set wkb = Workbooks("POD Automation10.2")
With wkb
Set sh1 = ActiveWorkbook.Sheets("POD Cost Plan")
Set sh2 = ActiveWorkbook.Sheets("Development Calculator")
Set sh3 = ActiveWorkbook.Sheets("Calculator Calculations")
sh1.Select
Set tbl = ActiveSheet.ListObjects("POD_CostPlan_Tbl")
Set rng = Range("POD_CostPlan_Tbl[#All]").Resize(tbl.Range.Rows.Count + Value, tbl.Range.Columns.Count)
tbl.Resize rng
sh2.Select
Set tbl = ActiveSheet.ListObjects("TBL_UserEntry")
Set rng = Range("TBL_UserEntry[#All]").Resize(tbl.Range.Rows.Count + Value, tbl.Range.Columns.Count)
tbl.Resize rng
sh3.Select
Set tbl = ActiveSheet.ListObjects("TBL_Calculations")
Set rng = Range("TBL_Calculations[#All]").Resize(tbl.Range.Rows.Count + Value, tbl.Range.Columns.Count)
tbl.Resize rng
End With
End Sub
A better approach would be to use ListObject properties to add rows and columns. For example:
With ActiveSheet.ListObjects("Table1")
' Insert column at the end of table:
.ListColumns.Add
' Add row tp the bottom of table:
.ListRows.Add AlwaysInsert:= True
End With
If I were you, I would change all those to Tables, so everything (rows and columns) gets updated automatically.
https://www.thespreadsheetguru.com/blog/2014/6/20/the-vba-guide-to-listobject-excel-tables
Ctrl+T: This shortcut converts a range of related information to an Excel Table. To use this shortcut, just select any cell in a range of related data first.
I am having an issue with my pivot tables. For some reason, this code was working this morning but now it is not. Here is my code up until the error.
Dim WSD2 As Worksheet
Set WSD2 = ActiveWorkbook.Sheets.Add(After:= _
Worksheets(Worksheets.Count))
WSD2.Name = "POS Info"
'--------------------------------------------------
' Step 2: Create the pivot table
'--------------------------------------------------
Dim WSD As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PRange As Range
Dim FinalRow As Long
Dim FinalCol As Long
Dim StartPT As String
Dim BottomRowStart As Range ' this is for pivot table
Dim BottomRowEnd As Range ' this is for pivot table
Set WSD = Worksheets("aggregateData")
' Select the data for pivot table
FinalRow = WSD.Cells(Rows.Count, 2).End(xlUp).Row
FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = WSD.Cells(2, 1).Resize(FinalRow, FinalCol)
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion14)
'Where do I want the pivot table to start
StartPT = WSD2.Range("A1").Address(ReferenceStyle:=xlR1C1)
Set WSD2 = Worksheets("POS Info")
'Begin to Create the Pivot Table
Set PT = PTCache.CreatePivotTable(TableDestination:=StartPT, TableName:="POS Data")
The last line is where I get the following error message:
"Application-defined or object-defined error".
Any help would be much appreciated.
Thanks,
G
Like #GSerg said in the comment, TableDestination needs to be a range instead of an address.
Right now you assign an address to the TableDestination, which really is just a string (text) saying "$A$3" or similar. You need to change this to TableDestination:=WSD2.range(StartPT) and then you code should work.
Note that it is possible that this worked previously but not any more because you may have added more worksheets to the document. Then when VBA tries to understand the address "$A$3" it cannot decide which worksheet to use and hence throws an error. It's therefore always smart to be quite clear when referring to ranges, and to do it via their workbook.worksheets path. See here for more.
I have a bunch of sheets with detailed data sets and pivot tables. On a summary sheet, I want to display just the pivot tables. (Of course, I'd rather stay DRY and not create a whole new set.) How can I reference the old pivot tables?
I can use VBA to do this if necessary.
This sub will keep the pivot tables 'live.' You could PasteValues over them if you don't want that.
Sub SummarizePivotTables()
Dim wb As Workbook, ws As Worksheet, ss As Worksheet, pt As PivotTable
Dim pasteRow As Long
Const rowsBetween As Long = 1
Set wb = ThisWorkbook
Set ss = wb.Worksheets("Summary")
pasteRow = 1 'first table row'
For Each ws In wb.Worksheets
For Each pt In ws.PivotTables
'change this to TableRange1 if you do not want the page field included'
With pt.TableRange2
.Copy ss.Range("A" & pasteRow)
pasteRow = pasteRow + .Rows.Count + rowsBetween
End With
Next pt
Next ws
End Sub
Pivot tables are named "Excel tables" in your workbook. So you should be able to do this without VB as I described in this answer.
tl;dr;
Data -> Get External Data -> Existing Connections
Goto "Tables" tab, select your table
Insert as "Table"