Excel VBA that Creates a Pivot Table - vba

I have this macro that takes all of sheet1 and creates a pivot table of it. However, it is currently only looking at the amount of rows I had when I made it and not the entire sheet no matter how many rows it has that day. Is there any way to make it select all of sheet1 as the pivot table data every time?
If possible I would also like to alter the fix duplicates to be the entire column based on the column name (IDNUMBER) if able.
Range("$A$1:$AM$2428")
Range("$A$1:$AM$4000")
"PIVOT_STATE_REPORT!R1C1:R1048576C39"
Sub PIVOT_STATE()
'
' PIVOT_STATE Macro
'
'
'ActiveSheet.Range("$A$1:$AM$2428").RemoveDuplicates Columns:=36, Header:= _
'xlYes
Columns("AJ:AJ").Select
ActiveSheet.Range("$A$1:$AM$4000").RemoveDuplicates Columns:=36, Header:= _
xlYes
Range("A2").Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"PIVOT_STATE_REPORT!R1C1:R1048576C39", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("State (Corrected)")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Count"), "Sum of Count", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Claim Age in CS"), _
"Sum of Claim Age in CS", xlSum
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Days Since LHN"), _
"Sum of Days Since LHN", xlSum
Range("B3").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Count")
.Caption = "Count of Count"
.Function = xlCount
End With
Range("C3").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"Sum of Claim Age in CS")
.Caption = "Average of Claim Age in CS"
.Function = xlAverage
.NumberFormat = "0"
End With
Range("D3").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"Sum of Days Since LHN")
.Caption = "Average of Days Since LHN"
.Function = xlAverage
.NumberFormat = "0"
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("State (Corrected)")
End With
End Sub
Thanks in advance!

I would use the last row and column formulas provided in this function.
Then make the source a combo of these variables.
Function LastRowColumn(sht As Worksheet, RowColumn As String) As Long
'PURPOSE: Function To Return the Last Row Or Column Number In the Active
Spreadsheet
'INPUT: "R" or "C" to determine which direction to search
Dim rc As Long
Select Case LCase(Left(RowColumn, 1)) 'If they put in 'row' or column instead of 'r' or 'c'.
Case "c"
LastRowColumn = sht.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Case "r"
LastRowColumn = sht.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
Case Else
LastRowColumn = 1
End Select
End Function
Then inside of your macro call out:
x = LastRowColumn(ActiveSheet, "column")
y = LastRowColumn(ActiveSheet, "Row")
plast = cells(x,y)
Then make a range based off that for the source of the pivot table
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"PIVOT_STATE_REPORT!A1:" & plast, Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion15

I think the easiest way of doing this will be to replace these lines of your code
Columns("AJ:AJ").Select
ActiveSheet.Range("$A$1:$AM$4000").RemoveDuplicates Columns:=36, Header:=xlYes
Range("A2").Select
With
Dim rData As Range: Set rData = ActiveSheet.Range("A1", ActiveSheet.Range("A1").End(xlDown))
Set rData = Range(rData, rData.End(xlToRight))
rData.RemoveDuplicates Columns:=36, Header:=xlYes
ActiveWorkbook.PivotCaches.Create SourceType:=xlDatabase, SourceData:=rData
The update this be where you make your PivotCache
`
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"PIVOT_STATE_REPORT!R1C1:R1048576C39", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion15c
`
With the following code using the rData range as the Source Data
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
rData, Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
, DefaultVersion:=xlPivotTableVersion15
Note this assumes that there are no gaps in the columns or rows of your Data. The End(xlDown) is the equivalent of holding the Ctrl and Down key

Related

Overwrite sheet if it exists

I recorded a macro that makes some pivot tables in a new sheet and it works fine, so i tried to make it able to overwrite if the sheet already existed but i can't seem to make it work. The problem is that when i use the macro once it does add the new sheet but it also adds another one on top of the one already made, and when i try to use the macro again to see if it overwrites the other one, it doesn't it just adds another unnamed sheet.
The code looks like this:
Sub Makro7()
Sheets.Add After:=ActiveSheet
On Error Resume Next
Sheets.Add().Name = "Statistics"
On Error GoTo 0
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Base!R1C1:R18288C12", Version:=6).CreatePivotTable TableDestination:= _
"Statistics!R1C1", TableName:="Pivottabel22", DefaultVersion:=6
Sheets("Statistics").Select
Cells(1, 1).Select
ActiveSheet.PivotTables("Pivottabel22").AddDataField ActiveSheet.PivotTables( _
"Pivottabel22").PivotFields("FACULTY_ID"), "Antal af FACULTY_ID", xlCount
With ActiveSheet.PivotTables("Pivottabel22").PivotFields("FACULTY_ID")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel22").PivotFields("PROGRAM_TYPE_NAME")
.Orientation = xlRowField
.Position = 1
End With
Range("A1").Select
ActiveSheet.PivotTables("Pivottabel22").DataPivotField.PivotItems( _
"Antal af FACULTY_ID").Caption = "Antal"
Range("B1").Select
ActiveSheet.PivotTables("Pivottabel22").CompactLayoutColumnHeader = "Fakultet"
Range("A7").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel22").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R7C1", TableName:= _
"Pivottabel23", DefaultVersion:=6
Sheets("Statistics").Select
Cells(7, 1).Select
ActiveSheet.PivotTables("Pivottabel23").AddDataField ActiveSheet.PivotTables( _
"Pivottabel23").PivotFields("FACULTY_ID"), "Antal af FACULTY_ID", xlCount
With ActiveSheet.PivotTables("Pivottabel23").PivotFields("PROGRAM_TYPE_NAME")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel23").PivotFields("FACULTY_ID")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel23").PivotFields("Antal af FACULTY_ID")
.Calculation = xlPercentOfTotal
.NumberFormat = "0.00%"
End With
Range("A7").Select
ActiveSheet.PivotTables("Pivottabel23").DataPivotField.PivotItems( _
"Antal af FACULTY_ID").Caption = "Procentvis"
Range("B7").Select
ActiveSheet.PivotTables("Pivottabel23").CompactLayoutColumnHeader = "Fakultet"
Range("A13").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel23").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R13C1", TableName:= _
"Pivottabel24", DefaultVersion:=6
Sheets("Statistics").Select
Cells(13, 1).Select
ActiveSheet.PivotTables("Pivottabel24").AddDataField ActiveSheet.PivotTables( _
"Pivottabel24").PivotFields("ENROLL_LOCATION_NAME"), _
"Antal af ENROLL_LOCATION_NAME", xlCount
With ActiveSheet.PivotTables("Pivottabel24").PivotFields("ENROLL_LOCATION_NAME" _
)
.Orientation = xlRowField
.Position = 1
End With
Range("B13").Select
ActiveSheet.PivotTables("Pivottabel24").DataPivotField.PivotItems( _
"Antal af ENROLL_LOCATION_NAME").Caption = "Antal"
Range("A13").Select
ActiveSheet.PivotTables("Pivottabel24").CompactLayoutRowHeader = "Campus"
Range("B13").Select
ActiveSheet.PivotTables("Pivottabel24").DataPivotField.PivotItems("Antal"). _
Caption = "Antal af studerende"
Range("A22").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel24").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R22C1", TableName:= _
"Pivottabel25", DefaultVersion:=6
Sheets("Statistics").Select
Cells(22, 1).Select
ActiveSheet.PivotTables("Pivottabel25").AddDataField ActiveSheet.PivotTables( _
"Pivottabel25").PivotFields("ENROLL_LOCATION_NAME"), _
"Antal af ENROLL_LOCATION_NAME", xlCount
With ActiveSheet.PivotTables("Pivottabel25").PivotFields("ENROLL_LOCATION_NAME" _
)
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("Pivottabel25").PivotFields( _
"Antal af ENROLL_LOCATION_NAME")
.Calculation = xlPercentOfTotal
.NumberFormat = "0.00%"
End With
Range("A22").Select
ActiveSheet.PivotTables("Pivottabel25").CompactLayoutRowHeader = "Campus"
Range("B22").Select
ActiveSheet.PivotTables("Pivottabel25").DataPivotField.PivotItems( _
"Antal af ENROLL_LOCATION_NAME").Caption = "Procentvis af studerende"
Range("I1").Select
ActiveWorkbook.Worksheets("Statistics").PivotTables("Pivottabel25").PivotCache. _
CreatePivotTable TableDestination:="Statistics!R1C9", TableName:= _
"Pivottabel26", DefaultVersion:=6
Sheets("Statistics").Select
Cells(1, 9).Select
ActiveSheet.PivotTables("Pivottabel26").AddDataField ActiveSheet.PivotTables( _
"Pivottabel26").PivotFields("STUDYBOARD_ID"), "Antal af STUDYBOARD_ID", xlCount
With ActiveSheet.PivotTables("Pivottabel26").PivotFields("STUDYBOARD_ID")
.Orientation = xlRowField
.Position = 1
End With
Range("I1").Select
ActiveSheet.PivotTables("Pivottabel26").CompactLayoutRowHeader = "Studienævn"
Range("J1").Select
ActiveSheet.PivotTables("Pivottabel26").DataPivotField.PivotItems( _
"Antal af STUDYBOARD_ID").Caption = "Antal af studerende"
Range("L15").Select
End Sub
The problem is this piece of code:
Sheets.Add After:=ActiveSheet
On Error Resume Next
Sheets.Add().Name = "Statistics"
On Error GoTo 0
This basically tells Excel to add a new sheet after the active sheet and when you run the macro the second time, the sheetname "Statistics" is already taken. (And if it wasn't for On error resume next, an error message would appear the second time). Add this at the top of your macro instead:
Dim newSheet As Worksheet
Application.DisplayAlerts = False
Set newSheet = Sheets.Add(After:=ActiveSheet)
With newSheet
On Error Resume Next
ThisWorkbook.Sheets("Statistics").Delete
On Error GoTo 0
.name = "Statistics"
End With
Application.DisplayAlerts = True

Run-time error 1004 cannot open pivottable source file

I'm new at VBA and Macros. Following Macro Recording, I ended up with this bug.
The file name is available on desktop with the correct name.
Thanks for any help,
Sub Macro2435Pivot()
'
' Macro2435Pivot Macro
'
'
Cells.Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"2435_Monthly Sales with Adjustm'!1:15000", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Sheet2!R3C1", TableName:= _
"PivotTable" & [=round(Rand()*1000,0)], DefaultVersion:=xlPivotTableVersion15
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Month")
.Orientation = xlPageField
.Position = 1
End With

Excel VBA Reference SourceData for Creating Pivot Table

I need help!
In order to convert a table to a list I am using the following VBA formula. It was created by using record macro and the PivotTable Wizard (not the most elegant solution), but it works.
ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:= _
Array("PasteSheet!R1C1:R300C200"), Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="", TableName:="PivotTable3", _
DefaultVersion:=xlPivotTableVersion14
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
ActiveSheet.PivotTables("PivotTable3").DataPivotField.PivotItems( _
"Count of Value").Position = 1
ActiveSheet.PivotTables("PivotTable3").PivotFields("Row").Orientation = _
xlHidden
ActiveSheet.PivotTables("PivotTable3").PivotFields("Column").Orientation = _
xlHidden
Range("A4").Select
Selection.ShowDetail = True
My issue is I want to be able to set the SourceData to reference a stored variable as the source data range will change each time the macro is run, but I can't get it to work and googled everywhere with no result. My best shot was trying the following.
Dim newRange As Variant
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Set newRange = Selection
ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:= _
newRange, Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="", TableName:="PivotTable3", _
DefaultVersion:=xlPivotTableVersion14
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
ActiveSheet.PivotTables("PivotTable3").DataPivotField.PivotItems( _
"Count of Value").Position = 1
ActiveSheet.PivotTables("PivotTable3").PivotFields("Row").Orientation = _
xlHidden
ActiveSheet.PivotTables("PivotTable3").PivotFields("Column").Orientation = _
xlHidden
Range("A4").Select
Selection.ShowDetail = True
Help would be much appreciated!
You need to reference the source array differently. I am sure there is a better way than my example below, but this does work
Dim newRange As Range
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
newRange = Selection
ActiveWorkbook.PivotCaches.Create(SourceType:=xlConsolidation, SourceData:= Array("R" & newRange.Row & "C" & newRange.Column & ":R" & newRange.Row + newRange.Rows.Count - 1 & "C" & newRange.Column + newRange.Columns.Count - 1), Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="", TableName:="PivotTable3", DefaultVersion:=xlPivotTableVersion14
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(3, 1)
ActiveSheet.Cells(3, 1).Select
ActiveSheet.PivotTables("PivotTable3").DataPivotField.PivotItems("Count of Value").Position = 1
ActiveSheet.PivotTables("PivotTable3").PivotFields("Row").Orientation = xlHidden
ActiveSheet.PivotTables("PivotTable3").PivotFields("Column").Orientation = xlHidden
Range("A4").Select
Selection.ShowDetail = True
I stumbled on this post as I was looking for a solution to a similar problem
anyways. to answer to this old post. I might help someone else.
The SourceData can be addressed in two ways. either the one that witchild used:
"nameofyourworksheet!R1C1:R" & Nbroftherowsofthesourcedataorarray & "C17", Version:=xlPivotTableVersion15).CreatePivotTable _'
or, the 2nd way:
ActiveWorkbook.Worksheets("nameofyourworksheet").Range("A1:Q" & Nbroftherowsofthesourcedataorarray).Address(, , xlR1C1, True), Version:=xlPivotTableVersion15).CreatePivotTable _
The code line: .Address(, , xlR1C1, True) means that the range will be converted to the format "R..C.." to make it works. I didnt try it but I trust the forum :p
hope I was able to help people searching for a solution to this problem

Excel VBA - Stuck on generating pivot table from variable data range

I have the code below which theoretically should create a pivot table on a 2nd sheet (which exists) using the data it finds on the 'DATA' sheet. However it always crashes as soon as it reaches the part to create the pivot table.
I originally come from a fixed size and afterwards changed it so it should take all the data on my 'DATA' sheet regardless of whether it's a 2x3 or 58x13 table
Sheets("DATA").Select
Range("H1").Select
ActiveCell.FormulaR1C1 = "l"
Range("A1").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets("DATA").Range("A1").CurrentRegion, _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Prior. per user!R1C1", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14
Sheets("Prior. per user").Select
Cells(1, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Priority")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Caller")
.Orientation = xlRowField
.Position = 1
End With
Range("D2").Select
ActiveSheet.PivotTables("PivotTable1").PivotFields("Priority").PivotItems( _
"Medium").Position = 2
Columns("D:D").ColumnWidth = 7.43
Columns("C:C").ColumnWidth = 10
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Number"), "Sum of Number", xlSum
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Number")
.Caption = "Count of Number"
.Function = xlCount
End With
If anyone sees what's wrong with it, it would be much appreciated.
Your target sheet name has spaces in it so you need to enclose it in single quotes:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets("DATA").Range("A1").CurrentRegion, _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="'Prior. per user'!R1C1", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14
Personally, I would also use a variable to refer to the pivot table:
Dim PT As PivotTable
Set PT = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets("DATA").Range("A1").CurrentRegion, _
Version:=xlPivotTableVersion14).CreatePivotTable(TableDestination:="'Prior. per user'!R1C1", TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14)
With PT
With .PivotFields("Priority")
.Orientation = xlColumnField
.Position = 1
End With
With .PivotFields("Caller")
.Orientation = xlRowField
.Position = 1
End With
.PivotFields("Priority").PivotItems("Medium").Position = 2
.Parent.Columns("D:D").ColumnWidth = 7.43
.Parent.Columns("C:C").ColumnWidth = 10
.AddDataField .PivotFields("Number"), "Count of Number", xlCount
End With

recorded macro gives runtime error 5

I'm new with VBA.
I recorded a macro an d wanted to edit it. after recording it, I wanted to run it one time. But when I did, it returned the Runtime Error 5.
The Macro should take and from a sheet and add it into a pivottable in another sheet.
So this is the code, where the error is based.
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"sourcetable!R1C1:R1048576C21", Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Tabelle2!R3C1", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion14
thanks for your help
no it doesn't it's a new sheet only for this pivot #SiddharthRout – beginner 4 mins ago
The simplest way to do is
With ActiveWorkbook
.Sheets("Tabelle2").Cells.Clear
.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"sourcetable!R1C1:R1048576C21", Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Tabelle2!R3C1", TableName:= _
"PivotTable1", DefaultVersion:=xlPivotTableVersion14
End With
Also I noticed that you have source data defined till the row 1048576. Why so? A more perfect way would be to find the last row and then construct your range. For example
Sub Sample()
Dim lRow As Long
With ActiveWorkbook
'~~> Find last row in sheet sourcetable
With .Sheets("sourcetable")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
lRow = 1
End If
End With
.Sheets("Tabelle2").Cells.Clear
.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="sourcetable!R1C1:R" & _
lRow & _
"C21", _
Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Tabelle2!R3C1", _
TableName:="PivotTable1", _
DefaultVersion:=xlPivotTableVersion14
End With
End Sub
First: does sourcetable and Tabelle2 worksheets exist?
Then, try it removing all optional meaningless arguments:
ActiveWorkbook.PivotCaches.Create(xlDatabase, "sourcetable!R1C1:R1048576C21") _
.CreatePivotTable ActiveWorkbook.Worksheets("Tabelle2").Range("R3C1")