Create a pivot table in a predefined location - excel

I'm trying to create a pivot table and place it in a predefined location (not a new sheet).
Before running the macro each time, the pivot table is deleted and also the predefined sheet.
I noticed that when you create a table manually, the table name increases by one each time (PivotTable2, PivotTable3...), which I think is where my code is falling down.
I get a Run-time error 5, invalid procedure call or argument on this line:
ActiveWorkbook.PivotCaches.Create
I did check out this thread, which says that you can remove the table name parameter completely, or rename it - however I still get errors.
My code:
Sub CreatePivot()'
' CreatePivot Macro
'
' Set data as table
Sheets("Filtered Flags").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$G$16000"), , xlYes).Name _
= "Table1"
' Create worksheet for pivot output
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Flag Pivot"
'Create Pivot Table
Sheets("Filtered Flags").Select
Range("Table1[[#Headers],[Order '#]]").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table1", Version:=6).CreatePivotTable TableDestination:="Flag Pivot!R3C1" _
, TableName:="PivotTable5", DefaultVersion:=6
Sheets("Flag Pivot").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable5").PivotFields("Material #")
.Orientation = xlRowField
.Position = 1
End With
End Sub

So there's a few things to work with here. One of the basics to get started with (and to understand why some of my example below is constructed) is to learn about avoiding the use of Select and Activate. Also, always using Option Explicit will help you sidestep many problems in naming and using variables.
Option Explicit
Public Sub CreatePivot()
'--- establish some basic objects to use...
Dim flagsWS As Worksheet
Set flagsWS = ThisWorkbook.Sheets("Filtered Flags")
'--- now, define the range of cells that contain the data
' and create the pivot cache
With flagsWS
Dim lastRow As Long
Dim lastCol As Long
Dim dataArea As Range
Dim dataAreaString As String
lastRow = .Cells(.Cells.rows.count, 1).End(xlUp).Row
lastCol = .Cells(1, .Cells.Columns.count).End(xlToLeft).Column
Set dataArea = .Range(.Cells(1, 1), .Cells(lastRow, lastCol))
dataAreaString = .Name & "!" & dataArea.Address
Dim pCache As PivotCache
Set pCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=dataAreaString)
End With
'--- create or clear the sheet for our new pivot
Dim pivotWS As Worksheet
On Error Resume Next
Set pivotWS = ThisWorkbook.Sheets("Flag Pivot")
On Error GoTo 0
If Not pivotWS Is Nothing Then
'--- delete everything on the worksheet so we're starting clean
pivotWS.Cells.Clear
Else
Set pivotWS = ThisWorkbook.Sheets.Add
pivotWS.Name = "Flag Pivot"
End If
'--- finally create the pivot table
Dim flagPT As PivotTable
Set flagPT = pivotWS.PivotTables.Add(PivotCache:=pCache, _
TableDestination:=pivotWS.Range("A4"), _
TableName:="AnnasPivotTable")
End Sub

Related

Invalid procedure call or argument when running VBA code to create a pivot table [duplicate]

I searched the internet code and was able to put together a macro to create a pivot table through VBA. I keep getting a Run time error '5': Invalid procedure call or argument when it gets to the creating the Pivot Table cache.
Set myPivotTable = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=mySourceWorksheet.Name & "!" & mySourceData).CreatePivotTable(TableDestination:=myDestinationWorksheet.Name & "!" & myDestinationRange, TableName:="TBPvt")
I have this same code create another pivot table and it works fine. I put both sets of code side by side and the only updates between the code is myDestinationWorksheet and the TableName in the code above. So I'm not sure what I did wrong.
Sub CreateTBpvt()
'declare variables to hold row and column numbers that define source data cell range
Dim myLastRow, myLastColumn As Long
Dim StartHere As String
StartHere = Sheets("Start Here").Range("C3").Value
'declare variables to hold source and destination cell range address
Dim mySourceData As String
Dim myDestinationRange As String
'declare object variables to hold references to source and destination worksheets, and new Pivot Table
Dim mySourceWorksheet As Worksheet
Dim myDestinationWorksheet As Worksheet
Dim myPivotTable As PivotTable
'identify source and destination worksheets
With ThisWorkbook
Set mySourceWorksheet = .Worksheets("TrialBalance")
Set myDestinationWorksheet = .Worksheets("TB Pivot")
End With
'obtain address of destination cell range
myDestinationRange = myDestinationWorksheet.Range("A1").Address(ReferenceStyle:=xlR1C1)
With mySourceWorksheet.Cells
'find last row and last column of source data cell range
myLastRow = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
myLastColumn = .Find(What:="*", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'obtain address of source data cell range
mySourceData = .Range(.Cells(2, "A"), .Cells(myLastRow, myLastColumn)).Address(ReferenceStyle:=xlR1C1)
End With
'create Pivot Table cache and create Pivot Table report based on that cache
Set myPivotTable = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=mySourceWorksheet.Name & "!" & mySourceData).CreatePivotTable(TableDestination:=myDestinationWorksheet.Name & "!" & myDestinationRange, TableName:="TBPvt")
'add, organize and format Pivot Table fields
With myPivotTable
.PivotFields("Account").Orientation = xlPageField
.PivotFields("Descr").Orientation = xlRowField
With .PivotFields(StartHere)
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0.00"
End With
End With
End Sub
The destination sheet has a space in its name, so you need to surround it with single quotes:
TableDestination:="'" & myDestinationWorksheet.Name & "'!" & myDestinationRange

Currently writing code to create a pivot table that will show the count of IDS that are within a city under a county. My macro only creates a sheet

I got the code from elsewhere and tried to adapt it to my worksheet but it only creates a blank sheet and not the table. I am thinking that there is some error when it tries to get grab the data from the source sheet.
Is there a different way to to fix it or maybe create this table if we can't fix it? Like for example the data is dynamic meaning that each report has a different amount of rows and perhaps later on columns.
for ex:
ID
Name
city
County
23423
Jdoe
d city
d County
That said there are about 30 other columns that are in the report and in the future there may or may not be more columns. The amount of rows number in the 10s of thousands and can be different week to week. I am trying to create a pivot table put an ID to the city they are in and the county it is listed under. I have already created or adapted a different macro to format the document in how we can use it but the pivot table is the last step. Please help!!!
'Declare Variables
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
' Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
'define worksheet
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data")
' Define Data Range
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:="CountyTable")
' Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="CountyTable")
'Insert Row "County" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields("PATIENT_COUNTY")
.Orientation = xlRowField
.Position = 1
End With
'Insert Row "City" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields("PATIENT_CITY")
.Orientation = xlRowField
.Position = 2
End With
'Insert Values "Count of PID" Field
With ActiveSheet.PivotTables("CountyTable").PivotFields( _
"Sum of PATIENT_LOCAL_ID")
.Caption = "Count of PATIENT_LOCAL_ID"
.Function = xlCount
End With
'Format Pivot Table
ActiveSheet.PivotTables("CountyTable").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("CountyTable").TableStyle2 = "PivotStyleMedium9"
End Sub

Create a table with a macro

I have this simple range:
I want to create a macro which creates a table from a range. The macro I get is this:
Sub Macro1()
'
' Macro1 Macro
'
'
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$B$3"), , xlYes).Name = _
"Table12"
ActiveCell.Range("Table12[#All]").Select
End Sub
The problem is that I want the macro to not be contingent on a specific size. I for instance want it to be able to work with this table as range aswell:
The problem in the code seems that it uses "$A$1:$B$3" but it should be independent of that. Is there a simple way to fix this? How can I record the macro so that it works for all tables?
The next piece of code will create a table ("MyTable") starting from the active cell to the adjacent most right column and to the down filled row of active cell column:
Sub TableRightDownOfSelection()
Dim rnG As Range
UnlistIt
Set rnG = Range(ActiveCell.Address & ":" & Cells(Cells(Rows.count, _
ActiveCell.Column).End(xlUp).Row, ActiveCell.End(xlToRight).Column).Address)
ActiveSheet.ListObjects.Add(xlSrcRange, rnG, , xlYes).Name = "MyTable"
End Sub
Sub UnlistIt()
On Error Resume Next
ActiveSheet.ListObjects("Table1").Unlist
If Err.Number > 0 Then Err.Clear
On Error GoTo 0
End Sub
In order to avoid an error message, in case you try the code again, the UnlistIt Sub will be called before creating the table...
You could use the currentregion property
Sub CreateTbl()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim rg As Range
Set rg = ws.Range("A1").CurrentRegion
ws.ListObjects.Add(xlSrcRange, rg, , xlYes).Name = "myTable"
End Sub
But be aware this code will create a table named like myTable_1 in case you already have a table namend myTable somewhere else and it will faill if you run it twice for the same range.
Addition: Based on the comments one could try to use the active cell
Sub CreateTbl()
Dim ws As Worksheet
Dim rg As Range
Set rg = ActiveCell.CurrentRegion
Set ws = rg.Parent
ws.ListObjects.Add(xlSrcRange, rg, , xlYes).Name = "myTable"
End Sub

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

VBA -Place Pivot Table in Same worksheet

New to VBA and I am having difficulty with my Macro creating a pivot table on the same worksheet with my data (for example, starting the pivot table in the "I1" column). I have been able to run the macro to select all of the data within the sheet and then create this data on another worksheet. Since I will need to loop through a number of worksheets on the same workbook to create multiple pivot tables, having separate sheets isn't feasible.
Each worksheet has the same number of columns with a varying number of rows. My goal is to have this macro look at each worksheet and output a pivot table next to it.
I feel like the macro I have below is not referencing the correct pivot Table destination. Any assistance would be appreciated.
Sub Macro4()
'
'Macro4 Macro
'
'
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
DataSheet & "!R1C1:R" & FinalRow & "C8", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:=DataSheet & "!R1C9", TableName:= _
"PivotTable4", DefaultVersion:=xlPivotTableVersion15
Sheets(DataSheet).Select
Cells(1, 9).Select
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Document Type")
.Orientation = xlRowField.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Accounting Event")
.Orientation = xlRowField.Position = 2
End With
With ActiveSheet.PivotTables("PivotTable4").PivotFields("Document Number")
.Orientation = xlRowField.Position = 3
End With
ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables
( _"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
End Sub
Try the code below, it's with a little different approach, defining Range, PivotTable, PivotCache, and you can modify them easily according to your needs:
Sub Macro4()
Dim FinalRow As Long
Dim DataSheet As String
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
Dim DataRng As Range
Dim TableDest As Range
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
DataSheet = ActiveSheet.Name
' set data range for Pivot Table
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 8)) ' conversion of R1C1:R & FinalRow & C8
' set range for Pivot table placement
Set TableDest = Sheets(DataSheet).Cells(1, 9) ' conversion of R1C9
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, DataRng)
' this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables("PivotTable4") ' check if "PivotTable4" Pivot Table already created (in past runs of this Macro)
On Error GoTo 0
If PvtTbl Is Nothing Then ' "PivotTable4" doesn't exist >> create it
' create a new Pivot Table in "PivotTable4" sheet
Set PvtTbl = ActiveWorkbook.Sheets(DataSheet).PivotTables.Add(PivotCache:=PvtCache, TableDestination:=TableDest, TableName:="PivotTable4")
With PvtTbl.PivotFields("Document Type")
.Orientation = xlRowField
.Position = 1
End With
With PvtTbl.PivotFields("Accounting Event")
.Orientation = xlRowField
.Position = 2
End With
With PvtTbl.PivotFields("Document Number")
.Orientation = xlRowField
.Position = 3
End With
PvtTbl.AddDataField ActiveSheet.PivotTables( _
"PivotTable4").PivotFields("Amount"), "Sum of Amount", xlSum
Else
' just refresh the Pivot cache with the updated Range
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub

Resources