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

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.

Related

set workbooks and worksheets returns either "nothing" or 424 run-time error object required

I am desperately hoping someone can help me. I've been troubleshooting this issue for the last 3 days non-stop. I am new to VBA so I am sure it has to be something elementary. Basically I have 2 open workbooks, one holds the data, and the other is where I want to paste some of the data based on an "if, then". For some reason, I cannot set the workbooks as variables in order to easily reference/update. I know we will be changing the name of these 2 documents as soon as I am able to go live, so I wanted to just change it in one place instead of all throughout the code. Below is the code, can someone please tell me what I'm missing? The comments are included to help make the picture clear. I look forward to hearing any wisdom that you could impart?
Dim I As Integer
'NAMING AND ASSIGNING TYPE WORKBOOKS AND WORKSHEETS FOR EASIER REFERENCE
Dim wbraw As Workbook
Dim wsrawwires As Worksheet
Dim wbdest As Workbook
Dim wsdestwires As Worksheet
Dim wsdestcover As Worksheet
'SETTING LOCATION OF NAMED WORKBOOKS AND WORKSHEETS FOR CODING
Set wbraw = Workbooks("scorecard (raw data) revised.xlsx")
Set wbdest = Workbooks("scorecard revised.xlsm")
Set wsrawwires = wbraw.Sheets("wires")
Set wsdestwires = ThisWorkbook.Sheets("sheet2")
Set wsdestcover = ThisWorkbook.Sheets("cover")
'NAMING AND LOCATING VARIABLE FOR CONDITION OF IF STATEMENT
previousyear = Workbooks("scorecard revised.xlsm").Range("x10")
'NAMING AND LOCATING VARIABLE FOR SOURCE TESTED IN IF STATEMENT
rawwiresfinalrow = wsrawwires.Range("b537").End(xlUp).Row
For I = 3 To rawwiresfinalrow
'CODE FOR PULLING APPLICABLE DATA INTO DESTINATION REPORT
If wsrawwires.Range(Cells(I, 5)).Value = previousyear.Value Then
wsrawwires.Range(Cells(I, 2), Cells(I, 5)).Copy
wsdestwires.Range("a1").PasteSpecial xlPasteValues
End If
Next I
First things first, I would always recommend using Option Explicitwhich basically stops the code from running if not all variables are defined. This makes debugging easier and you will find typos straight away.
So use this instead:
Option Explicit
Sub nameOfSub()
Dim i As Long 'use Long instead of Integer.
Dim rawwiresfinalrow as Long
Dim counter As Long
'NAMING AND ASSIGNING TYPE WORKBOOKS AND WORKSHEETS FOR EASIER REFERENCE
Dim wbraw As Workbook
Dim wsrawwires As Worksheet
Dim wbdest As Workbook
Dim wsdestwires As Worksheet
Dim wsdestcover As Worksheet
Dim previousyear As Range
'SETTING LOCATION OF NAMED WORKBOOKS AND WORKSHEETS FOR CODING
Set wbraw = Workbooks("scorecard (raw data) revised.xlsx")
Set wbdest = Workbooks("scorecard revised.xlsm")
Set wsrawwires = wbraw.Sheets("wires")
Set wsdestwires = ThisWorkbook.Sheets("sheet2")
Set wsdestcover = ThisWorkbook.Sheets("cover")
'NAMING AND LOCATING VARIABLE FOR CONDITION OF IF STATEMENT
Set previousyear = wbdest.Sheets("Enter_your_sheetname_here").Range("x10")
'NAMING AND LOCATING VARIABLE FOR SOURCE TESTED IN IF STATEMENT
rawwiresfinalrow = wsrawwires.Range("b537").End(xlUp).Row
counter = 1
For i = 3 To rawwiresfinalrow
'CODE FOR PULLING APPLICABLE DATA INTO DESTINATION REPORT
If wsrawwires.Cells(I, 5).Value = previousyear.Value Then
With wsrawwires
.Range(.Cells(i, 2), .Cells(i, 5)).Copy
End With
wsdestwires.Range("A" & counter).PasteSpecial xlPasteValues
counter = counter + 1
End If
Next I
End Sub

Trying to create pivot table vba with dynamic range

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)

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

Copy value form sheet, use as worksheet names (in a loop) - VBA Excel Macro

I am attempting to Copy values in a Row, one by one from each cell, then use those values as worksheet names, one by one. One of the issues I had was skipping the first batch of sheets, so I attempted to hide the ones I don't want renamed. All other sheets should be renamed (34 of them).
I can get it all the way "ws.PasteSpecial xlPasteValues" using F8 before I get an error message that says "Run-time error '1004'L Method 'PasteSpecial' of object'_Worksheet' failed.
I have also tried using "Activesheet.PasteSpecial xlPasteValues" but it gave the same error.
Any suggestions at all are very much appreciated, this is driving me nuts. :) My back up plan is simply using the macro record and doing every rename manually, but it's not a very elegant or simple code that way, so I'd prefer not to do that.
Here is the Code:
Dim ws As Worksheet
Dim TitleID As String
Dim TID As String
Sheets("SheetName1").Activate
Set ws = ActiveSheet
Dim rng As Range, cell As Range
Set rng = ws.Range("C5", "AJ5")
For Each cell In rng
cell.Copy
Sheets("SheetName1").Visible = False
ws.Next.Select
ws.PasteSpecial xlPasteValues
Next cell
If I understand your question, properly, the below code should work.
Dim ws As Worksheet
Set ws = Sheets("SheetName1")
Dim rng As Range, cell As Range
Set rng = ws.Range("C5","AJ5")
Dim i as Integer
i = 5 'this is an arbitrary number, change to whatever number of worksheets
'you wish to exclude that are at the beginning (left most side) of your workbook
'also assumes "SheetName1" is before this number.
For Each cell In rng
Sheets(i).Name = cell.Value
i = i + 1
Next cell

VBA: Naming a Range

I have searched for a solution but can't seem to find one. If one exists, please point me to it.
The question is how do I name a range in VBA.
wrkSheet.Range("A1").Name = "Test"
Works fine but as soon as I change it to
wrkSheet.Range("A1:B2").Name = "Test"
gives me problems. Note, wrkSheet is a worksheet object that is defined earlier.
Thanks
you can use this to name a range. Not sure why wrkSheet is a string as it should be a worksheet object
Dim ws As Worksheet
Dim r As Range
Set ws = Sheets(1)
Set r = ws.Range("A1:B2")
r.Name = "test"
You're not naming a range there... you giving values to a excel range of cells...
To name a range you do
range = wrkSheet.Range("A1:B2").Name
Then you can do range(1,1) = "test" for example.