Creating Dynamic Range in Pivot Table - excel

I'm trying to change my fixed range (A1:G4193) to one that's dynamic due to the need for new data to be entered on a daily basis.
Here is my code:
Sub Create_Pivot()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim pf As PivotField
SrcData = ActiveSheet.Name & "!" & Range("A1:G4193").Address(ReferenceStyle:=xlR1C1)
Set sht = Sheets.Add
StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
I highly appreciate any help. Thanks!

Assumption - your Pivot Table's dynamic range is changing by the number of rows added (or distracted), while the number of columns stays constant.
Instead of using ActiveSheet, try using referenced objects, like Set SrcSht = Worksheets("Sheet1") and then use that variable.
Try the code below (some of my other modifications are inside the code's notes).
Option Explicit
Sub Create_Pivot_DynamicRange()
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As Range
Dim SrcData As String
Dim pf As PivotField
Dim SrcSht As Worksheet, LastRow As Long
' modify "Sheet1" to your sheet's name
Set SrcSht = Worksheets("Sheet1")
With SrcSht
' find last row with data in Column A (skip blank cells in the middle)
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
' set source data to dynamic number of rows (string)
SrcData = .Name & "!" & .Range("A1:G" & LastRow).Address(ReferenceStyle:=xlR1C1)
End With
Set sht = Sheets.Add
' set the start position directly to a Range (there's no need to use a String as a "middle-man")
Set StartPvt = sht.Range("A1")
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
End Sub

Change your range to a variable - like RNG
The calculate the range , how ever you plan to do it. Last row, last column, last cell address, etc
Then make the code soething like this
Lastrow = ActiveSheet..Range("B" & Worksheets("All_Data").Rows.Count).End(xlUp).Row
RNG = "A1:"G" & Lastrow
SrcData = ActiveSheet.Name & "!" & Range(RNG).Address(ReferenceStyle:=xlR1C1)

Related

Trying to get Macro to automatically adjust DataRange for Pivot Table

I'm sorry if this is basic but I can't seem to figure this out .
Long story short my file has several tabs with lot's of data and each tab has a pivot table. What I need is a Macro that adjusts the data range of the Pivot table to the data in current sheet. I have it now set with a bigger range giving me Blanks which drives me nuts.
Here is my code :
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String
Dim LastCol As Long
Dim lastRow As Long
'Set Pivot Table & Source Worksheet
Set Data_Sheet = ThisWorkbook.Worksheets("1")
Set Pivot_Sheet = ThisWorkbook.Worksheets("1")
'Enter in Pivot Table Name
PivotName = "PivotTable1"
'Defining Staring Point & Dynamic Range
Data_Sheet.Activate
Set StartPoint = Data_Sheet.Range("V2")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))
NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
ActiveSheet.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange _
, Version:=6)
Now when I try this I get the "Run time error -2147024809" error stating that The pivottable name is invalid .
This updates all the sheets that have 1 pivot table
Sub Update()
Dim wb As Workbook, ws As Worksheet
Dim rng As Range, cell As Range, newrange As String
Set wb = ActiveWorkbook
For Each ws In wb.Sheets
With ws
If .PivotTables.Count = 1 Then
Set cell = .Range("V2").End(xlToRight).End(xlDown)
Set rng = .Range("V2", cell)
newrange = "'" & ws.Name & "'!" & rng.Address(ReferenceStyle:=xlR1C1)
.PivotTables(1).ChangePivotCache _
wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=newrange, Version:=6)
End If
End With
Next
End Sub

Get data pivot table VBA

I have generated a pivot table with the following code.
Sub TCD()
Dim last_row As Integer
last_row = Cells(Rows.Count, 1).End(xlUp).Row
Dim My_range As Range
Set My_range = Range(Cells(1, 1), Cells(last_row, 2))
Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim pf_Name As String
'Create a new worksheet
Set sht = Sheets.Add
sht.Name = "TCD"
'Where do you want Pivot Table to start?
StartPvt = "TCD" & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1)
'Create Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=My_range)
'Create Pivot table from Pivot Cache
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
pvt.PivotFields("Type_c").Orientation = xlRowField
pf_Name = "Max iteration par type"
pvt.AddDataField pvt.PivotFields("Nb_Iteration"), pf_Name, xlMax
'Part of code that does nothing
Dim dbl As Double
dbl = pvt.GetData(Name:="CP")
End Sub
The pivot table looks like this
How can I retrieve the number of each row element ? I have tried using get data (last two lines of code) and getpivotdata. Nothing seems to work.
You can try the following:
dbl = pvt.GetData("'Max iteration par type' CP")

How can I create a dynamic range for a pivot table?

I am trying to write a macro that creates a pivot table on a new sheet based on data from a master spreadsheet. How can I adjust my code to do this?
I've gotten the code to work with static data but whenever the data is dynamic, the macro does not work. I believe the issue is with the first line starting with "srcData = ". The line below, which is commented out, works without any issues.
Option Explicit
Dim pivotSht As Worksheet
Dim dataSht As Worksheet
Dim pCache As PivotCache
Dim pTable As PivotTable
Dim srcData As String
Dim pRange As Range
Dim lastR As Long
Dim lastC As Long
Public Sub buildPivot()
Set dataSht = Worksheets("OOB")
'Defines data range in "OOB" sheet
With dataSht
lastR = .Cells(.Rows.Count, "D").End(xlUp).Row
lastC = .Cells(4, .Columns.Count).End(xlToLeft).Column
Set pRange = .Range(.Cells(1, "D1"), Cells(lastR, lastC))
End With
Sheets("OOB").Activate
srcData = ActiveSheet.Name & "!" & pRange.Address(ReferenceStyle:=xlR1C1)
'srcData = ActiveSheet.Name & "!" & Range("D1:U714").Address(ReferenceStyle:=xlR1C1)
'Delete old "PivotTable" worksheet if it exists
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
'Create new sheet and name it "PivotTable"
Set pivotSht = Sheets.Add
ActiveSheet.Name = "PivotTable"
'Set location of pivot table
startPvt = pivotSht.Name & "!" & pivotSht.Range("A3").Address(ReferenceStyle:=xlR1C1)
'Define pivot cache
Set pCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=srcData)
'Creates pivot table from pivot cache
Set pTable = pCache.CreatePivotTable( _
tabledestination:=startPvt, _
TableName:="Open Order Book Table")
End Sub
The expected output is a pivot table using all data as the source, even with changing data.

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