VBA issue with creating pivot cache - excel

I am struggling to find a solution to the issue I am having; I've been looking all over. I'm not sure if it is how I am obtaining my first row or if it is something else. I have the exact same code (below) setup for another macro but that macro pulls R1C1:lastrow/lastcol. The only difference is: this macro attempts to use a dynamic first row (instead of Set PRange = glData.Cells(1, 1).Resize(LastRow, LastCol)) . I've even tried setting the first row as R10C1(the header row of the source data) and I still get an "Application-defined or object-defined error".
Macro use: Creates pivot table based on source data in range A(y):N(x); x = dynamic lastrow/col, y = dynamic first row. Destination is 4 columns to the right of another pivot table(created by a different sub). They will not overlap (unless something is hidden). I have made this setup manually and it works fine.
Any help is appreciated.
Sub CreateFAPiv()
'
Dim PSheet As Worksheet
Dim wsData As Worksheet: Set wsData = Sheets("Data")
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Dim asset As String
Dim glData As Worksheet: Set glData = Sheets("GL")
asset = glData.Range("B2").Value
Set PSheet = Worksheets("Piv")
'Define Data Range
FirstRow = IIf(IsEmpty(glData.Range("C1")), glData.Range("C1").End(xlDown).Row, 1)
LastRow = glData.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = glData.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = glData.Cells(FirstRow, 1).Resize(LastRow, LastCol)
'Define Pivot Cache - This is where I am getting the error
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(3, 4), _
TableName:="DataPivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(3, 4), TableName:="DataPivotTable")
.....Rest of code....
End Sub

Related

Fetching data from a different worksheet in Excel VBA

I'm trying to source data from a separate sheet in excel but the second reference to Ws_Names brings up Runtime Error 1004. How would I correctly source values for a range from another sheet?
Dim Ws_Names As Worksheet
Set Ws_Names = Worksheets("Names")
Dim Ws_Data As Worksheet
Set Ws_Data = Worksheets("Data")
Dim SubTechs As Long, Names_range As Range
SubTechs = Ws_Names.Cells(Rows.Count, 1).End(xlUp).Row 'this works
Set Names_range = Ws_Names.Range(Cells(1, 1), Cells(SubTechs, 2)) 'this doesn't work
It's because when you don't put a leading reference it assumes Activesheet
What
Set Names_range = Ws_Names.Range(Cells(1, 1), Cells(SubTechs, 2)) 'this doesn't work
Actually says is, and your current activesheet isn't Ws_Names
Set Names_range = Ws_Names.Range(Activesheet.Cells(1, 1), Activesheet.Cells(SubTechs, 2))
So the solution is
Set Names_range = Ws_Names.Range(Ws_Names.Cells(1, 1), Ws_Names.Cells(SubTechs, 2))

Create Pivot Table Based on Dynamic Range

I am trying to create a macro that will take data that starts at A18, find the last row and last column then generate a pivot table. I searched around to take bits and pieces from code I found online to try to make something work.
I keep getting a 1004 error, and I suspect it is because my code isn't actually selecting the data range properly.
this is the code that the error happens on:
Set pvtable = pvcache.CreatePivotTable(TableDestination:=pvsheet.Cells(1, 1), TableName:="Payroll")
this is all of the code:
Dim pvtable As PivotTable
Dim pvcache As PivotCache
Dim ptrange As Range
Dim pvsheet As Worksheet
Dim pdsheet As Worksheet
Dim plr As Long
Dim plc As Long
Dim startCell As Range
On Error Resume Next
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Worksheets("Pivot table").Delete 'to delete the existing pivot table in the worksheet
Worksheets.Add After:=ActiveSheet ' to add a new worksheet
ActiveSheet.Name = "Pivot Table" ' to rename the worksheet
On Error GoTo 0
Set pvsheet = Worksheets("Pivot table")
Set pdsheet = Worksheets("sheet1")
Set startCell = Range("A18")
'two variable to find Last used row and column in sheet 1, raw data'
plr = pdsheet.Cells(pdsheet.Rows.Count, startCell.Column).End(xlUp).Row
plc = pdsheet.Cells(startCell.Row, pdsheet.Columns.Count).End(xlToLeft).Column
'set range from selected data
Set ptrange = pdsheet.Cells(1, 1).Resize(plr, plc)
'pivot cahe needed for data load
Set pvcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, SourceData:=ptrange)
'create empty pivot table
Set pvtable = pvcache.CreatePivotTable(TableDestination:=pvsheet.Cells(1, 1), TableName:="Payroll")
'Insert worker to Row Filed
With pvsheet.PivotTables("Payroll").PivotFields("Worker")
.Orientation = xlRowField
.Position = 1
End With
'Insert Street to Row Filed & position 2
With pvsheet.PivotTables("Payroll").PivotFields("Actual Hours")
.Orientation = xlRowField
.Position = 2
End With
'to show the pivot table in Tabular form
pvsheet.PivotTables("Payroll").RowAxisLayout xlTabularRow
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I am suspecting the issue is within this area here where the data range is selected to make the pivot table:
Set pvsheet = Worksheets("Pivot table")
Set pdsheet = Worksheets("sheet1")
Set startCell = Range("A18")
'two variable to find Last used row and column in sheet 1, raw data'
plr = pdsheet.Cells(pdsheet.Rows.Count, startCell.Column).End(xlUp).Row
plc = pdsheet.Cells(startCell.Row, pdsheet.Columns.Count).End(xlToLeft).Column
'set range from selected data
Set ptrange = pdsheet.Cells(1, 1).Resize(plr, plc)
any help appreciated, thank you
Try defining your range as follows...
Set ptrange = pdsheet.Range(startCell, pdsheet.Cells(plr, plc))
Or, alternatively...
Set pdsheet = Worksheets("sheet1")
Set startCell = pdsheet.Range("A18")
With pdsheet
plr = .Cells(.Rows.Count, startCell.Column).End(xlUp).Row
plc = .Cells(startCell.Row, .Columns.Count).End(xlToLeft).Column
Set ptrange = .Range(startCell, .Cells(plr, plc))
End With

How to dynamically retrieve the range address of data then change the pivot table data source range address?

I am trying to dynamically retrieve the range address of data then change the pivot table data source range address.
There are three sheets involved.
1) ThisWorkbook.Worksheets("sheet1") - main dashboard, has pivot chart and slicer that were moved from sheet2
2) ThisWorkbook.Worksheets("sheet2") - Pivot Table
3) ThisWorkbook.Worksheets("sheet3") - source data that was copied from different workbook before the below code runs.
My code gives
Run-time error 5: Invalid Procedure call or argument
The error points to Set pt = Pivot_sht.PivotTables(PivotName).ChangePivotCache(pc)
I have two other pivot charts on my main sheet. Using the same code they refresh without any issues.
Full code:
Option Explicit
Sub test()
Dim daMa As Worksheet
Dim daPerf As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim DataRange As Range
Dim PivotName As String
Dim NewRangePH As String
Dim pt As PivotTable
Dim pc As PivotCache
'REFRESHING PERFORMANCE HISTORY
'Set Variables Equal to Data Sheet and Pivot Sheet
Set Data_sht = ThisWorkbook.Worksheets("sheet3")
Set Pivot_sht = ThisWorkbook.Worksheets("sheet2")
'Enter in Pivot Table Name
PivotName = "PHPivot"
With Data_sht
.Activate
'Dynamically Retrieve Range Address of Data
LastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
LastCol = 12
Set DataRange = Data_sht.Range(Cells(LastRow, 1).Address, Cells(1, LastCol).Address)
End With
NewRangePH = Data_sht.Name & "!" & _
DataRange.Address(ReferenceStyle:=xlR1C1)
'Make sure every column in data set has a heading and is not blank (error prevention)
If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then
MsgBox "One of your data columns has a blank heading." & vbNewLine _
& "Please fix and re-run!.", vbCritical, "Column Heading Missing!"
Exit Sub
End If
'Change Pivot Table Data Source Range Address
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRangePH)
Set pt = Pivot_sht.PivotTables(PivotName).ChangePivotCache(pc)
End Sub
I searched through many Google result and results from Stack Overflow and tried at least 10 different things before posting this question.
"set pt = " is worng, you do not want to set a new pivottable.
Instead use
Pivot_sht.PivotTables(PivotName).ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
newRangePH, Version:=xlPivotTableVersion15)

Empty Pivot Cache when creating a pivot table in VBA

I'm using code from https://excelchamps.com/blog/vba-to-create-pivot-table/ to create a pivot table in a long macro I'm writing. The pivot table recently stopped working; this sub runs with no errors but there is no sign of the pivot table. Was fully functional until recently. On trying to troubleshoot I've found the PCache variable is empty, I'm assuming this is where everything is breaking down. The only thing changed since this was working is I changed the cell formats of two columns in the data range for the pivot table, however they seem irrelevant and are not being used for the pivot table.
I have also recorded my own macro to try and fix this. Manually creating the pivot table works fine but this is not a solution to my problem. The recorded macro from this does not work however. I have tried code from multiple different sites as well and have used non-variable ranges but nothing has worked.
Sub bpPivotTBL()
'https://excelchamps.com/blog/vba-to-create-pivot-table/
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
'??Declare Variables
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PIPE PIVOT").Delete
Sheets.Add Before:=Worksheets("INCOMING")
ActiveSheet.Name = "PIPE PIVOT"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PIPE PIVOT")
Set DSheet = Worksheets("INCOMING")
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'=================================================================
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PipePivot")
'==================================================================
'?Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="PipePivot")
'Insert Row Fields
With ActiveSheet.PivotTables("PipePivot").PivotFields("CNCT")
.Orientation = xlRowField
.Position = 1
End With
The reason you're not getting an error is that you've included an On Error statement, which masks any errors. If you comment out or delete that line, you'll get an error here...
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="PipePivot")
That instruction first creates a pivot cache, then it creates a pivot table, and then it tries to assign the pivot table to PCache, which has been declared as a PivotCache. As a result, you'll get an error. So create only the pivot cache, and then assign it to PCache...
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange)
Try the code below, explanations inside the code's comments:
' =================================================================
' Set the Pivot Cache Range
Dim SrcData As String
SrcData = PRange.Address(False, False, xlA1, xlExternal)
' Define and Set the Pivot Cache
Set PCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'==================================================================
' create a new Pivot Table in "PIPE PIVOT" sheet
Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Range("A1"), TableName:="PipePivot")
'Insert Row Fields
With PTable.PivotFields("CNCT") ' <<-- Once you set the Pivot-Table, you can use this object in your With Statements
.Orientation = xlRowField
.Position = 1
End With

Pivot table creation failing with runtime error 1004

This code used to work on office 365. I am now working on office 2016 and I am getting a runtime error on the final line. The input to this is:
'Create a Pivot table called pt commission on sheet "Pivot Table" from the data on sheet2
Call ptSettings.CreatePivotTable("Pivot Table", Sheet2, "ptCommission")
The sub that is throwing the error on the final line is:
Sub CreatePivotTable(ptSheet As String, dSheet As Worksheet, ptName As String)
'Creates a pivottable called ptName on sheets(ptSheet) with the data from dsheet
Dim ptCache As PivotCache
Dim ptTable As pivotTable
Dim ptRange As Range
Dim lastRow As Long
Dim lastCol As Long
Application.DisplayAlerts = False
Worksheets(ptSheet).Delete
Sheets.Add before:=ActiveSheet
ActiveSheet.Name = ptSheet
Application.DisplayAlerts = True
lastRow = dSheet.Cells(Rows.Count, 2).End(xlUp).Row
lastCol = dSheet.Cells(2, Columns.Count).End(xlToLeft).Column
Set ptRange = dSheet.Cells(1, 1).Resize(lastRow, lastCol + 1)
Set ptCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=ptRange)
Set ptTable = ptCache.CreatePivotTable _
(TableDestination:=Sheets(ptSheet).Cells(3, 1), TableName:=ptName)
End Sub
Cheers for taking a look guys!
Just found out what was happening. There was data in the second row making the lastCol be higher than it needed to be. Then when I tried to create a pivot table from that range it threw the error because ptRange didnt have column headings.
I only realised after I tried running vs stepping through it and it came out with a different error.. Oh VBA.

Resources