Trying to create pivot table vba with dynamic range - vba

I want to create a pivot table with a dynamic range that refers to another tab. I keep getting "Run-time error '13' - Type mismatch" after the comment "define pivot cache". Any suggestions?
Sub InsertExportPivotTables()
'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
'*************Actions by study
'Insert a New Blank Worksheet for Actions by Study
Application.DisplayAlerts = False
Worksheets("Actions by Study").Delete 'deletes worksheet if already exists
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "Actions by Study"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Actions by Study")
Set DSheet = Worksheets("export")
'Define Data Range
LastRow = DSheet.Range("A" & DSheet.Rows.Count).End(xlUp).Row
Set PRange = DSheet.Range(DSheet.Cells(6, 1), DSheet.Cells(LastRow, "U"))
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion14)
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), _
TableName:="ActionsbyStudy01", DefaultVersion:=xlPivotTableVersion14)
End Sub

You can pass PivotCaches.Create a named range but not a Range object.
The SourceData argument is required if SourceType isn't xlExternal .
It should be passed a Range (when SourceType is either xlConsolidation
or xlDatabase ) or an Excel Workbook Connection object (when
SourceType is xlExternal ). When passing a Range, it is recommended to
either use a string to specify the workbook, worksheet, and cell
range, or set up a named range and pass the name as a string.
Passing a Range object may cause "type mismatch" errors unexpectedly.
(More info at Source)

Related

VBA Pivot Table; Error '1004' Refrence is not valid

I am creating a sheet that grabs data from another workbook and creates a pivot table based off the data.The error im running into is when I try to create the pivot table error '1004' Breaks the code, here is the line of code that breaks. If I attempt to fix the error it will instead run into a type mismatch error
Set rcPT = ActiveSheet.PivotTables.Add(PivotCache:=rcPTCache, TableDestination:=Range("A1"))
I am fairly certain it has something to do with the data range as it works when I use a different range but im not sure, it may be a easy fix and I just need another perspective. Here is the full code.
Dim wbReviewPivots As Workbook
Set wbReviewPivots = ActiveWorkbook
Dim wsPivots As Worksheet
Dim wbData As Workbook
Dim wsData As Worksheet
Dim endCell As Integer
Dim rcPT As PivotTable
Dim rcPTCache As PivotCache
Dim rcPlace As Range
' set variable equal to data sheet and pivot sheet
Set wbData = Workbooks.Open("//Workbook\\")
Set wsPivots = wbReviewPivots.Sheets("RootCausesCleaned")
Set wsData = Sheets("RawData") 'gets the last row within the rawdata sheet
endCell = wsData.Cells(Rows.Count, "A").End(xlUp).Row
'set the data range
wsData.Activate
Dim MyRange1 As Range, MyRange2 As Range, dataRange As Range
Set MyRange1 = Range("A1:E" & endCell)
Set MyRange2 = Range("G1:AA" & endCell)
Set dataRange = Application.Union(MyRange1, MyRange2)
'create root cause pivot chart
wbReviewPivots.Sheets("RootCausesCleaned").Activate
Set rcPTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=dataRange)
Set rcPT = ActiveSheet.PivotTables.Add(PivotCache:=rcPTCache, TableDestination:=Range("A1"))
With rcPT
.PivotFields("Cause").Orientation = xlRowField
.PivotFields("Cause (Sub Category)").Orientation = xlRowField
.PivotFields("Task ID").Orientation = xlDataField
End With
The dataRange excludes the G column because if its included another error is run into, Its not a required column so it doesn't matter if the columns excluded but I do think its making it difficult to create the pivot tables.
The excel table object could also be used, but this still runs into the same error.
You can't create a pivot table from non-contiguous ranges like you're trying to do by excluding column G.
Your Type Mismatch error is from trying to declare a PivotCache using a Range object for SourceData. This question, or this question, shows you how to use a String reference.
endCell should be a Long, not an Integer. (Just a thought, maybe use endRow or some other name, endCell sounds like a Range variable and might be misleading.)
Since dataRange is in a different workbook, you can use its Address with External:=True to get its full String reference including the workbook name. I'd use the xlR1C1 reference style since it sounds like A1-style can cause errors with larger data sets.
So to fix your errors, make these tweaks...
Dim dataAddress as String
Set dataRange = wsData.Range("A1:AA" & endCell) ' or maybe endRow
dataAddress = dataRange.Address(ReferenceStyle:=xlR1C1, External:=True)
Then within Set rcPTCache = ..., SourceData:=dataAddress.

Subscript Out of range VBA Error

I am new to vba. I am trying to copy header row from one sheet to newly created another sheet. I am getting an out of range error when try to select new worksheet. Below is the code i am using.
With Sheets("Details Master")
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim rngsource As Range
Dim rngDest As Range
Set ws1 = Sheets("Details Master")
'Sheets("Details Master").Select
Set rngsource = ws1.Range("B2:L2")
rngsource.Copy
End With
With Sheets("Sh_name") **'Error on this line**
Set ws2 = Sheets("Sh_name") 'Sh_name is newly created sheet name
Set rngDest = ws2.Range("B2:L2")
rngDest.PasteSpecial
End With
Any idea what might be the issue.
You failed to add the new worksheet, as #Storax and # ashleedawg commented.
When using this basic code, please change the new worksheet name from "Temp" to what you want your worksheet name to be. Also make sure the name in the Destination line is the same name.
With ThisWorkbook
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Temp"
Sheets("Details Master").Range("B2:L2").Copy Destination:=Sheets("Temp").Range("B2")
End With

Run-Time Error 1004 - Macro to update pivot table

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

Run time error 1004 "Cannot open PivotTable source file"

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

Type mismatch error while adding pivotcache

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