I want to create a pivot table based on a dataset (contained in a worksheet) in the same workbook.
The workbook is open when I run the macro. The dataset comes from running a query in Access, and then export it to excel. I also tried to save the workbook prior to running the macro. I am using excel 2016.
This is my code:
Sub BusinessInteligenceCreatePivotTable()
Dim PivotSheet As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
'Determine the data range you want to pivot
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsPartsMachines.Name & "'!" & wsPartsMachines.Range("A1").CurrentRegion.Address, Version:=xlPivotTableVersion15)
'Create a new worksheet
With ThisWorkbook
Set PivotSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
PivotSheet.Name = "Production Schedule"
End With
PivotSheet.Activate
Range("A1").Select
'Create Pivot table from Pivot Cache
'Set pvt = pvtCache.CreatePivotTable(TableDestination:=ActiveCell, TableName:="ProductionSchedule")
Set pvt = PivotSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=ActiveCell, TableName:="ProdSched")
End Sub
The two last lines generates the same error message. "Run time error 1004. Cant open PivotTable source file 'C:\Users...'".
Does anybody know how to solve this problem?
Thanks.
EDIT
When I record a macro, VBA gives me this code (it works).
Sub BusinessInteligenceCreatePivotTable()
Dim PivotSheet As Worksheet
With ThisWorkbook
Set PivotSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
PivotSheet.Name = "Production Schedule"
End With
PivotSheet.Activate
Range("A1").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Parts & Machines2!R1C1:R1328C14", Version:=6).CreatePivotTable _
TableDestination:=ActiveCell, TableName:="PivotTable1", DefaultVersion:=6
End Sub
I want my SourceData's range to be dynamically set. My efforts to do it generates (with debug.print): 'Parts & Machines2'!R1C1:R1328C14
It seems to be different from the macro-recorded :"Parts & Machines2!R1C1:R1328C14".
Is it this difference that generates the error that i cant find the source data?
Screenshot of Data.
I am not so sure where you define wsPartsMachines as Worksheet and where you set it.
However, the error is in the line:
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsPartsMachines.Name & "'!" & wsPartsMachines.Range("A1").CurrentRegion.Address, Version:=xlPivotTableVersion15)
If you add a line after:
Debug.Print pvtCache.SourceData
You will get 'Sheet3'''!R1C1:R6C3 in the immediate window - you have one ' too many. (I have used "Sheet3" as my SourceData)
Try to modify this line to :
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wsPartsMachines.Name & "!" & wsPartsMachines.Range("A1").CurrentRegion.Address)
Edit 1: Try a different approach, bring the data source direclty as Range:
Dim pvtDataRng As Range
Set wsPartsMachines = Sheets("Parts & Machines2")
' set the Pivot Table Data Source Range
Set pvtDataRng = wsPartsMachines.Range("A1").CurrentRegion
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pvtDataRng)
'Create Pivot table from Pivot Cache
Set pvt = PivotSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=ActiveCell, TableName:="ProdSched")
This code works. Still not sure why SourceData does not work. With small changes in the code that Shai Rado suggested it worked. Below is the code.
Sub BusinessInteligenceCreatePivotTable()
Dim PivotSheet As Worksheet
Dim pvtCache As PivotCache
Dim pvtTable As PivotTable
Dim ws1PartMachines As Worksheet
Dim pvtDataRng As Range
'Determine the data range you want to pivot
Set ws1PartsMachines = Worksheets("Parts & Machines2")
' set the Pivot Table Data Source Range
Set pvtDataRng = ws1PartsMachines.Range("A1").CurrentRegion
Set pvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=pvtDataRng)
Debug.Print pvtCache.SourceData
'Create a new worksheet
With ThisWorkbook
Set PivotSheet = .Sheets.Add(After:=.Sheets(.Sheets.Count))
PivotSheet.Name = "Production Schedule2"
End With
PivotSheet.Activate
Range("A1").Select
'Create Pivot table from Pivot Cache
Set pvtTable = PivotSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=ActiveCell, TableName:="ProdSched")
End Sub
Related
I am quite new to VBA and excel macros but want to automate certain reports for work and I am really hoping for someone's help. I tried to fix it myself by watching YouTube videos and reading stackoverflow but the solution didn't match with my issue. For now I created few macros but i am stuck with the one which should actually create a pivot table.
I first created a regular table out of the data I had (using TableP Macro beloew). It looks like it works fine (tested few other data sheets) :
Sub tableP()
'
' tableP Macro (Creates a table of the existing data sheet, regardless the data input)
'
ActiveCell.Cells.Select
ActiveCell.Activate
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$1:$1048576"), , xlYes).Name = _
"Table2"
ActiveCell.Cells.Select `
`End Sub `
The second macro (below) would ideally take that table (an object) and create a pivot table, however it crashes (excel stops working while I run the macro) each time I use a bigger dataset.
Sub Macro1test() '
' Macro1test creates dataset out of the existing table
'
Dim dataname As String
Dim Newsheet As String
dataname = ActiveSheet.ListObjects(1).Name
Sheets.Add
Newsheet = ActiveSheet.Name
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
dataname, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
:=Newsheet & "!R3C1", TableName:="PivotTable2", DefaultVersion:= _
xlPivotTableVersion14
Sheets.Select
Cells(3, 1).Select
End Sub
Can please someone let me know what am I doing wrong and what steps am missing to be able to apply those macros on any data set?
Try the code below, explanations inside the code's comments:
Option Explicit
Sub Macro1test()
' Macro1test creates dataset out of the existing table
'
Dim dataname As String
Dim RngStr As String
Dim Newsheet As String
Dim NewSht As Worksheet
Dim PvtCache As PivotCache
Dim PvtTbl As PivotTable
' set the Range String for the Pivot Cache Source Data)
RngStr = ActiveSheet.ListObjects(1).Range.Address(False, False, xlA1, xlExternal)
' add a new sheet
Set NewSht = ThisWorkbook.Sheets.Add(after:=ActiveSheet)
' set the Pivot Cache object
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=RngStr)
' set the New Pivot Table object
Set PvtTbl = NewSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=NewSht.Range("A3"), TableName:="PivotTable2")
End Sub
I am trying to update a pivot table using a macro since data is added to the bottom of the table each month (Update to include data to last row).
Option Explicit
Sub Pivot()
Dim shConD As Worksheet
Dim shPvtTbl As Worksheet
Dim lr As Long
Dim rng As Range
Set shConD = ActiveWorkbook.Sheets("Consolidated_Data")
Set shPvtTbl = ActiveWorkbook.Sheets("PivotTables")
lr = shConD.Range("A" & Rows.Count).End(xlUp).Row
Set rng = shConD.Range("A1:F" & lr)
With shPvtTbl.PivotTables(3).PivotCache
.SourceData = rng.Address(True, True, xlR1C1, True) 'Error appears here
.Refresh
End With
End Sub
On the .SourceData line, I am getting run-time error 1004, Application-defined or object-defined error. Followed logic from this thread and the continued chat . Thanks in advance guys.
If you're using Excel 2007 or later, then the simplest way to accomplish this is to make sure your PivotTable source data is an Excel Table (aka ListObject), and use the Table name in the Change PivotTable Data Source as shown below.
Thanks to the magic of Tables, from that point on, whenever you add new data to your Table, it will expand automatically. And whenever you refresh the PivotTable it will always pick up that new data automatically. There will be no need to change the PivotTable data source ever again.
Try the code below (explanation inside the code's comments) :
Option Explicit
Sub Pivot()
Dim shConD As Worksheet
Dim shPvtTbl As Worksheet
Dim lr As Long
Dim rng As Range
' Added PivotTable variables
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Set shConD = ActiveWorkbook.Sheets("Consolidated_Data")
Set shPvtTbl = ActiveWorkbook.Sheets("PivotTables")
lr = shConD.Range("A" & shConD.Rows.Count).End(xlUp).Row
Set rng = shConD.Range("A1:F" & lr)
' set/update the PivotCache (with latest rng modifications
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rng.Address(False, False, xlA1, xlExternal))
' for DEBUG Only
Debug.Print PvtCache.SourceData
' set the PivotTable object
Set PvtTbl = shPvtTbl.PivotTables(3)
' for DEBUG Only
Debug.Print PvtTbl.Name
' refresh the PivotTable with the updated PivotCache
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End Sub
I am trying to refresh automatically a pivot table with Powershell script that calls a vba code in an excel.
my powershell code is th following.
$excel = new-object -comobject excel.application
$workbook = $excel.workbooks.open("$para_temp\RapportPalettes.xlsm")
$worksheet = $workbook.worksheets.item("source")
$excel.Run('Import')
$worksheet = $workbook.worksheets.item("TCD")
$excel.Run('MAJ')
the first macro "Import" works just fine. But the second "MAJ" that refreshes the Pivot table with the new data in source doesn't
I tried first this macro in maj :
Sub maj()
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("TCD")
pt.RefreshTable
End Sub
I don't get any error but my pivote table isn't refreshed and i have to do it manually.
Then I tried this one to change the pivot table's source of data :
Sub MAJ()
Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache
'Determine the data range you want to pivot
Set sht = ThisWorkbook.Worksheets("Source")
SrcData = sht.Name & "!" & Range("A1:Z10000").Address(ReferenceStyle:=xlR1C1)
'Create New Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Change which Pivot Cache the Pivot Table is referring to
Worksheets("TCD").Activate
ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)
End Sub
but i have an 438 error in the VBA : object doesn't support this property or method for this line
ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)
could you please Help ?
EDIT :
as you can see, I do have a worksheet and a pivot table named TCD.
EDIT :
In fact the macro is working, i tested it by creating a button that calls it.
It doesn't work when i call it with powershell
Try the code below to refresh the PivotTable named "TCD" in worksheet "TCD" with the updated PivotCache.
Code
Option Explicit
Sub MAJ()
Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache
Dim pvtTbl As PivotTable
'Determine the data range you want to pivot
Set sht = ThisWorkbook.Worksheets("Source")
SrcData = sht.Range("A1:Z10000").Address(False, False, xlA1, xlExternal)
'Create New Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Set the pivot table object
Set pvtTbl = ThisWorkbook.Worksheets("TCD").PivotTables("TCD")
With pvtTbl
.ChangePivotCache pvtCache 'Change which Pivot Cache the Pivot Table is referring to
.RefreshTable ' refresh the Pivot Table
End With
End Sub
I finally found the problem which was a bit stupid. In fact I was refreshing the Pivot Table but I wasn't saving the changes.
This is the macro I finally used and I used the same powershell script:
Sub Test()
Application.DisplayAlerts = False
Dim TCD As PivotTable
For Each TCD In Worksheets("TCD").PivotTables
TCD.RefreshTable
Next
ThisWorkbook.Save
Application.DisplayAlerts = False
End Sub
Thanks for all
This returns type mismatch error I don't know why.
I asked the same questing yesterday in which I found there were some merged cells hence I removed merge cells today but still it's not working giving the same error
The code works fine with other sheet data but it returns the error for that specific sheet.
I tried this:
Set wD = Sheets.Add
ThisWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=wS.UsedRange).CreatePivotTable _
TableDestination:=wD.Range("A3")
And this
Set wD = Sheets.Add
ThisWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=wS.Range("A1").CurrentRegion).CreatePivotTable _
TableDestination:=wD.Name & "!R3C1"
This is what source data sheet looks like
Try the code below:
Sub UpdatePivot()
Dim wD As Worksheet
Dim wS As Worksheet
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim PvtRangeStr As String
Set wS = Sheets("inventory master")
Set wD = Sheets.Add
PvtRangeStr = "'" & wS.Name & "'!" & wS.UsedRange.Address
' for debug
Debug.Print PvtRangeStr
' set Pivot Cache using another reference to the range
Set PvtCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PvtRangeStr, Version:=xlPivotTableVersion14)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = wD.PivotTables("PivotTable1")
On Error GoTo 0
If PvtTbl Is Nothing Then
' create a new Pivot Table in wD Sheet, start from Cell A3
Set PvtTbl = wD.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=wD.Range("A3"), TableName:="PivotTable1")
Else
' just refresh the Pivot cache with the updated data
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End If
End Sub
Hi I have a pivot table set up which I need to refresh on a VBA command. However when I refresh the pivot command it excludes some of the required Column label Values. I believe I have to change the Pivot Cache which was set up originally but not sure how to? (Can anyone advise how to do this?)
The code I am using is below:
Worksheets("Summary by Account").PivotTables("PivotTable1").RefreshTable
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
For Each pt In ActiveSheet.PivotTables
pt.ManualUpdate = True
pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
For Each pf In pt.PivotFields
If pf.Orientation <> 0 Then
If pf.Orientation = xlPageField Then
pf.CurrentPage = "(All)"
Else
For Each pi In pf.PivotItems
pi.Visible = True
Next pi
End If
End If
Next pf
pt.ManualUpdate = False
Next pt
Set pi = Nothing
Set pf = Nothing
Set pt = Nothing
Set wks = Nothing
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Nominal / Category")
.PivotItems("(blank)").Visible = False
End With
I am using the following code to refresh my PIVOT Table Cache, my source file is located in a remote workbook, so you can adjust the parameters to your needs.
Const Pivot_sht_str As String = "Summary by Account"
Const Pivot_name_str As String = "PivotTable1"
Dim pt As PivotTable
Dim Data_FilePath As String
Dim Data_book As String
Dim Data_sht_str As String
Dim Data_sht As Worksheet
Dim Data_range As Range
Dim Data_range_str As String
Dim lrow As Long
' Asign Pivot table to pt
Set pt = Worksheets(Pivot_sht_str).PivotTables(Pivot_name_str)
' Asign Pivot's Data source parameters >> this part is needed only if source for PIVOT table is data in another workbook
Data_FilePath = "\\Folder\Nested Folder\Nested Folder 2\" 'modify to your needs
Data_book = "File_Name.xlsx" 'modify to your needs
Data_sht_str = "Worksheet Name" 'modify to your needs
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
Workbooks.Open (Data_FilePath & Data_book)
Set Data_sht = ActiveWorkbook.Worksheets(Data_sht_str)
lrow = Data_sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Data_range_str = Data_sht.Name & "!" & Range("$A$1:$P$" & lrow).Address '.Address(ReferenceStyle:=xlR1C1) ' adjust Columns to your needs
Set Data_range = Data_sht.Range(Data_range_str)
' check if Data Range consists of a legal range, Workbook and worksheet are legal
If Not Data_range Is Nothing Then
Data_range_str = Data_FilePath & "[" & Data_book & "]" & Data_sht.Name & "!" & Range("$A$1:$P$" & lrow).Address
'Change Pivot Table Data Source Range Address (refresh it's cache data)
pt.ChangePivotCache ThisWorkbook.PivotCaches.Create(xlDatabase, Data_range_str, xlPivotTableVersion12) ' verify last parameter to have the correct Excel version
pt.RefreshTable
On Error Resume Next
ActiveWorkbook.Close (False) ' Workbooks(Data_FilePath & Data_book).Close savechanges:=False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Data_range Is Nothing Then Exit Sub
My method to updating pivot caches with new information is to store all of the data on a separate sheet within the workbook and put in an extending range formula named range - with this formula
=OFFSET($A$1,0,0,COUNTA($A:$A),COUNTA($1:$1))
Then, in VBA, use:
ThisWorkbook.RefreshAll
Hope that helps!
I use this code to reset all pivot table caches in the entire workbook and prevent the pivot table drop-down filters from showing missing items that don't actually exist in the underlying data.
Sub PivotCacheReset()
' When a data set is pivoted and then some of the underlying data is
' removed, even after a refresh old removed values can still remain in the
' pivot filter. This macro changes the properties of all pivot tables in
' the active workbook, to prevent missing items from appearing, or clear
' items that have appeared. It also resets all pivot table caches in the
' active workbook.
Dim wb As Workbook
Set wb = ActiveWorkbook
Dim iWs As Worksheet
Dim pvt As PivotTable
Dim iProtectState As Boolean
' Loop through each worksheet.
For Each iWs In wb.Worksheets
' If the worksheet is protected, unprotect it. Remember
' it was protected so that it can be re-protected later.
iProtectState = False ' Reset variable that remembers if each sheet is protected.
If iWs.ProtectContents = True Then
' Worksheet is protected.
iWs.Unprotect ' Unprotect the worksheet.
iProtectState = True ' Remember that this worksheet was protected.
End If
' Loop through each pivot table in the sheet.
For Each pvt In iWs.PivotTables
pvt.PivotCache.MissingItemsLimit = xlMissingItemsNone ' Don't allow missing items in the pivot table filters.
pvt.PivotCache.Refresh ' Reset the pivot table cache including any missing items.
Next pvt
' If the worksheet was originally protected, re-protect it.
If iProtectState = True Then iWs.Protect
Next iWs
End Sub