VBA Excel, Updateing pivot - excel

I have 3 pivot tables on 2 sheets in over 30 files so i tried to use vba to update them automatically. Problem is that i get an error 438. I don't know why it appears. My code:
Sub update()
Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache
Sheets("Raw Data").Select
SrcData = ("Raw Data") & "!" & Range("$A$9:$M$100000").Address(ReferenceStyle:=xlR1C1)
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
Sheets("Cost Week_Month").Select'This contain 2 tables, the same source data
ActiveSheet.PivotTables("PivotTable1").ChangePivotCache (pvtCache)
Sheets("View Week_Month").Select
ActiveSheet.PivotTables("PivotTable10").ChangePivotCache (pvtCache)
End Sub

It's probably this line:
SrcData = ("Raw Data") & "!" & Range("$A$9:$M$100000").Address(ReferenceStyle:=xlR1C1)
You're telling it to use R1C1 reference style, but supplying a "LetterNumber" reference.

Related

Pivot Table with Runtime Error '5' Invalid procedure call or argument

I copied a template to create a pivot table but adjusted it for a dynamic range due to reports being different in sizes at work. I keep getting Runtime Error '5' Invalid procedure call or argument as an error however when trying to create the pivot table from the pivot cache.
Can anyone please assist?
Thanks,
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As Range
'Determine the data range you want to pivot
Set SrcData = Sheet1.Range("A1").CurrentRegion
'ActiveSheet.Name & "!" &
'Range("A1:R100").Address(ReferenceStyle:=xlR1C1)
'Create a new worksheet
Set sht = Sheets.Add
With sht
.Name = "Payments Balancing"
End With
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" &
sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
End Sub

Run-Time Error 5 when creating a pivot table with vba

I am trying to create a pivot table but I keep running into an error.
Here is my code so far.
Sub Practice()
Dim wb As Workbook
Dim ws As Worksheet
Dim pvtc As PivotCache
Dim pvt As PivotTable
Dim str As String
str = "Jul 26"
Set wb = ActiveWorkbook
'Create Pivot Worksheet
Set ws = wb.Sheets.Add(After:=wb.Sheets(wb.Sheets.Count))
ws.Name = str
'Create Pivot Cache
Set pvtc = wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="Lignes!" & wb.Sheets("Lignes").Cells(1, 1).CurrentRegion.Address)
'Create Pivot Table
Set pvt = pvtc.CreatePivotTable( _
TableDestination:=ws.Name & "!" & ws.Cells(1, 1).Address, _
TableName:="Table1")
End Sub
The error occurs specifically at the last step when I create the pivot table.
What's wrong with it?
Edit: It was suggested I wrap my sheet name with single quotes (since it contains a space) if I pass a string to the TableDestination argument. I tried this
'Create Pivot Table
Set pvt = pvtc.CreatePivotTable( _
TableDestination:="'" & ws.Name & "'!A1", _
TableName:="Table1")
but I am still getting the same error.
Better to just use a Range object here:
TableDestination:=ws.Cells(1,1)

setting TableDestination while inserting pivot table through VBA

I am trying to insert a pivot table through VBA but get some issues with setting TableDestination.
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Src_Tbl, Version:=6). _
CreatePivotTable TableDestination:=ActiveWorkbook.ActiveSheet.Cells(PvtTbl_row_loc, PvtTbl_column_loc).Address(, , xlR1C1), TableName:="Summary", DefaultVersion:=6
I also tried this to debug:
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Src_Tbl, Version:=6). _
CreatePivotTable TableDestination:="'" & ActiveWorkbook.ActiveSheet.Name & "'!R4C10"
But I am getting
Expression not defined in context
Sub routine is called from a module which sets other variables.
To derive a PivotTable from a "table" (=ListObject) on each worksheet, you may use the ListObject itself as source data for the PivotCache:
Private Sub PivotTablesBasedOnListobjects()
Dim ws As Worksheet
Dim lo As ListObject
Dim pc As PivotCache
Dim pt As PivotTable
For Each ws In ActiveWorkbook.Worksheets
If ws.ListObjects.Count > 0 Then
Set lo = ws.ListObjects(1)
Set pc = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=lo)
Set pt = pc.CreatePivotTable( _
TableDestination:=ws.Cells(4, 10))
End If
Next ws
End Sub
The destination for the pivottable must not overlap the ListObject.Range, so you may compare its dimensions to define your "PvtTbl_row_loc" and "PvtTbl_column_loc".
You have to set a pivot cache and table, such that:
'Define Pivot Cache
Src_Tbl = "Sheet1!A1:B200" 'STRING
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Src_Tbl) 'removed ", Version:=6" for the sake of creating. can add in if needed
'Insert Blank Pivot Table
destloc = "'" & ActiveSheet.Name & "'!R4C10" 'STRING
Set pt = pc.CreatePivotTable(TableDestination:=destloc, TableName:="Report")
You may need to ensure that you're recognizing R1C1 notation with the destination location, ensuring the strings for source and destination are appropriate (can't be a range within VBA, e.g. range(cells(),cells())).
Edit1:
Showing the change from comments below this answer:
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Src_Tbl.Range)
The suggestion was to display as a String (my post) but was able to work around with the existing ListObject by using .Range
This is what finally worked. Many thanks to #Cyrill for his guidence-
Sub AddPvtTbl_Chart(Src_Tbl As ListObject, PvtTbl_row_loc, PvtTbl_column_loc As Integer)
Dim destloc, cell_in_RC As String
Dim pc As PivotCache
Dim pt As PivotTable
cell_in_RC = "R" & "" & PvtTbl_row_loc & "" & "C" & "" & PvtTbl_column_loc & ""
destloc = "'" & ActiveWorkbook.ActiveSheet.Name & "'!" & cell_in_RC & ""
Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Src_Tbl.Range)
Set pt = pc.CreatePivotTable(TableDestination:=destloc, TableName:="Summary")

VBA 2 Pivot Tables different sheets

I have searched the web, but I'm having trouble finding a solution to my issue. I have a workbook with 2 tabs of data. I am using VBA to create 2 pivot tables on 2 different sheets. The code runs through the first pivot table perfectly. The Second set of code for the second pivot table stops at the pivot Cache. Any ideas?
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim finRow As String
With ActiveWorkbook
finRow = Sheets("WorbookName").Range("A200000").End(xlUp).Row
SrcData = Sheets("WorkbookName").Name & "!" & Range("A1:I" & finRow).Address(ReferenceStyle:=xlR1C1)
`End With`
'Create a new worksheet
Set sht = Sheets.Add
'Pivot starting point?
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data`
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
Set pvt = ActiveSheet.PivotTables("PivotTable1")`
================ Second Pivot table code
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String`
'Pivot table range
Dim finRow As String
With Sheets("Data")
finRow = Sheets("Data").Range("A200000").End(xlUp).Row
SrcData = ActiveSheet.Name & "!" & Range("A3:CB" & finRow).Address(ReferenceStyle:=xlR1C1)`
End With
'Create a new worksheet
Set sht = Sheets.Add
'Where do you want Pivot Table to start?
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data`
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable2")
Any help provided is much appreciated. Thank you, Matt
At this point in your code, ActiveSheet is where you placed the previous pivot table, not on the sheet where you are intending to pull data. In both cases you use a With statement, but do not use.
Dim finRow As String
With Sheets("Data")
finRow = Sheets("Data").Range("A200000").End(xlUp).Row
SrcData = ActiveSheet.Name & "!" & Range("A3:CB" & finRow).Address(ReferenceStyle:=xlR1C1)`
End With
Try modifying...
Dim finRow As Long
With Sheets("Data")
finRow = .Range("A200000").End(xlUp).Row
SrcData = .Range("A3:CB" & finRow).Address(ReferenceStyle:=xlR1C1)`
End With

Excel macro Add-in duplicate spreadsheet pop up

My macro creates a pivot table from scratch from a set data dump. I am trying to move this macro to an add-in. the add-in works on the new data each time, but for some reason it pops up a second workbook that my code originally worked on.
I've read through add-in websites to make sure I set up the add-in correctly. My other add-in macro works (only have 2. still learning)
Sub OpenAndHoldPivot()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
'Determine the data range you want to pivot
Dim finRow As String
With ActiveWorkbook
finRow = ActiveSheet.Range("A200000").End(xlUp).Row
SrcData = ActiveSheet.Name & "!" & Range("A4:BO" & finRow - 1).Address (ReferenceStyle:=xlR1C1)
End With
'Create a new worksheet
Set sht = Sheets.Add
'Pivot Table Start
StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
'------------------------------------------------------------------------------
Set pvt = ActiveSheet.PivotTables("PivotTable1")
'Add item to the Report Filter
pvt.PivotFields("Future Fill Date").Orientation = xlPageField
'Add item to the Column Labels
pvt.PivotFields("Worker Type").Orientation = xlColumnField
'Add item to the Row Labels
pvt.PivotFields("Flex Division").Orientation = xlRowField
'Turn on Automatic updates/calculations --like screenupdating to speed up code
pvt.ManualUpdate = False
'------------------------------------------------------------------------------
ActiveSheet.Name = "Pivot"
'------------------------------------------------------------------------------
Dim pf As String
Dim pf_Name As String
pf = "FT/PT"
pf_Name = "Sum of FT/PT"
Set pvt = ActiveSheet.PivotTables("PivotTable1")
pvt.AddDataField pvt.PivotFields("FT/PT"), pf_Name, xlCount
'------------------------------------------------------------------------------
Dim pm As PivotField
Set pm = ActiveSheet.PivotTables("PivotTable1").PivotFields("Future Fill Date")
'Clear Out Any Previous Filtering
pm.ClearAllFilters
'Filter on 2014 items
pm.CurrentPage = "(blank)"
'------------------------------------------------------------------------------
Sheets("Sheet1").Name = "Data"
End Sub
Any ideas on what I am doing wrong?
I really think your problem lies with some inconsistent refernces (or lack of refernces) to which workbook or worksheet you're using. Specifically, I believe the problem is with the line
Set sht = Sheets.Add
Since your Sheets reference doesn't specify which workbook to add the new worksheet, it will default to the currently active workbook which could be your add-in workbook. You'll help yourself a great deal if you become much clearer about which workbooks and worksheets you want. To illustrate this using your example, you can start with
Sub OpenAndHoldPivot()
Dim workingWB As Workbook
Dim workingWS As Worksheet
Set workingWB = ActiveWorkbook
Set workingWS = activeworksheet
'Determine the data range you want to pivot
Dim srcData As Range
Dim srcDataText As String
With workingWS
Dim finRow As Long
finRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set srcData = .Range("A4").Resize(finRow - 1, 67)
srcDataText = .Name & "!" & srcData.Address(ReferenceStyle:=xlR1C1)
End With
This establishes clearly which workbook all your code will operate. Also, if you take a look at my With block and compare it to yours, you can see you missed a . before the Range reference, which again will likely refer back to either your add-in or the active workbook (and you can never be too sure.
After that, I just continue down the code...
'Create a new worksheet in the working workbook
Dim pivotWS As Worksheet
Set pivotWS = workingWB.Sheets.Add
'Pivot Table Start
Dim StartPvtText As String
StartPvtText = pivotWS.Name & "!" & pivotWS.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Dim pvtCache As PivotCache
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcDataText)
'Create Pivot table from Pivot Cache
Dim pvt As PivotTable
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvtText, _
TableName:="PivotTable1")
Notice also that I declare all my variables as close to where they're used as possible. This makes it much easier to follow and to be certain you're using the correct variable with the intended type.
Further on down your code, you've referred to the ActiveSheet a few times. Replace that with a specific reference in order to be consistent. In my code, I rarely use ActiveSheet or ActiveCell. I attempted to fix the references below here in the full module, but only you can tell if this is accurate (because it's not perfectly clear which book or sheet you want).
Finally, there's the very last line of code Sheets("Sheet1").Name = "Data". I have no idea which workbook that should reference, but my guess is that it should be workingWB.Sheets("Sheet1").Name = "Data".
Option Explicit
Sub OpenAndHoldPivot()
Dim workingWB As Workbook
Dim workingWS As Worksheet
Set workingWB = ActiveWorkbook
Set workingWS = activeworksheet
'Determine the data range you want to pivot
Dim srcData As Range
Dim srcDataText As String
With workingWS
Dim finRow As Long
finRow = .Cells(.Rows.Count, 1).End(xlUp).Row
Set srcData = .Range("A4").Resize(finRow - 1, 67)
srcDataText = .Name & "!" & srcData.Address(ReferenceStyle:=xlR1C1)
End With
'Create a new worksheet in the working workbook
Dim pivotWS As Worksheet
Set pivotWS = workingWB.Sheets.Add
'Pivot Table Start
Dim StartPvtText As String
StartPvtText = pivotWS.Name & "!" & pivotWS.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Dim pvtCache As PivotCache
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcDataText)
'Create Pivot table from Pivot Cache
Dim pvt As PivotTable
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvtText, _
TableName:="PivotTable1")
'------------------------------------------------------------------------------
Set pvt = pivotWS.PivotTables("PivotTable1")
'Add item to the Report Filter
pvt.PivotFields("Future Fill Date").Orientation = xlPageField
'Add item to the Column Labels
pvt.PivotFields("Worker Type").Orientation = xlColumnField
'Add item to the Row Labels
pvt.PivotFields("Flex Division").Orientation = xlRowField
'Turn on Automatic updates/calculations --like screenupdating to speed up code
pvt.ManualUpdate = False
'------------------------------------------------------------------------------
pivotWS.Name = "Pivot"
'------------------------------------------------------------------------------
Dim pf As String
Dim pf_Name As String
pf = "FT/PT"
pf_Name = "Sum of FT/PT"
Set pvt = pivotWS.PivotTables("PivotTable1")
pvt.AddDataField pvt.PivotFields("FT/PT"), pf_Name, xlCount
'------------------------------------------------------------------------------
Dim pm As PivotField
Set pm = pivotWS.PivotTables("PivotTable1").PivotFields("Future Fill Date")
'Clear Out Any Previous Filtering
pm.ClearAllFilters
'Filter on 2014 items
pm.CurrentPage = "(blank)"
'------------------------------------------------------------------------------
workingWB.Sheets("Sheet1").Name = "Data"
End Sub

Resources