Get Source Range of a PivotTable - vba

I am building a set of reports to be updated daily for some users who are not super savvy when it comes to pivot charts and pivot tables in Excel (2010). I have data from an already automated data pull from our db, but to make that information useful (and more simple to use), I want to generate the pivots using VBA.
I have already generated the pivot tables just fine and can manually manipulate them to create the relevant charts. As I create the tables (all on one sheet), I am labeling them (if that helps solve my problem). Where I am running into trouble is creating the pivot charts, and specifically, setting the data source.
Since the charts are based on pivots that may change in size depending on the data present, I can't just assign a fixed range as the source. Same problem with a named range, as I still don't know what range to assign a name, unless I can assign a PT as a range.
I've tried something like this, but that didn't work, since I'm not looking at an actual 'Range' object:
Dim MyChartObject As ChartObject
Dim MyChart As Chart
'These variables are assigned elsewhere in the code.
Set MyChartObject = wksMainCharts.ChartObjects.Add( _
iChartLeft, iChartTop, iChartWidth, iChartHeight)
Set MyChart = MyChartObject.Chart
MyChart.SetSourceData wksMainPivot.PivotTables(PivotName).SourceData 'Fails; requires Range object
'More code to follow...
I do know that this is a string representation of the wrong range, but I was playing with what I could figure on my own.
Essentially what I want is the opposite of this question, which seeks to find the pivot table at a specified range. I also reviewed this question, but it's not quite what I'm looking for (there are also no answers provided).
Also: I'm asking here for a way to get the range of a PT, which I think would be interesting to know, but ultimately, I just want to create the pivot chart, so if anyone wants to offer a better method than what I've started on, I'm completely open to that as well.

Is this what you are trying to achieve?
Sub Sample()
Dim Chrt As Chart, pvtTbl As PivotTable
Set pvtTbl = ActiveSheet.PivotTables(1)
Set Chrt = ActiveSheet.ChartObjects(1).Chart
Chrt.SetSourceData Source:=pvtTbl.TableRange1
End Sub
So your this line
MyChart.SetSourceData wksMainPivot.PivotTables(PivotName).SourceData
becomes
MyChart.SetSourceData wksMainPivot.PivotTables(PivotName).TableRange1

Related

Filling a variant array with charts in Excel VBA

I am working on a file that creates up to 120 charts based on data, variables, and format selections from the user. To do this I create a variant array to hold the charts which allows me to easily reference them for adding data, formatting, etc. This method has worked well for me so far.
Now I would like to let users make small tweaks to formatting (adjust the min and max on the axis, add or remove legend entries, etc.). To do this I would like to continue referencing the charts from an array, but I can't seem to add the existing charts to the variant array.
When I initially create the charts I use this line to add the chart to the array when it is created. I fill in appropriate parameters to place and size the chart and this seems to work fine.
Set charts(graphIndex) = activeSheet.ChartObjects.Add(...)
After creating all the charts, I think the non Global variables used are cleared from the cache (at least that is my current understanding). This means that in order to make these tweaks I need to reinitialize and redefine the variant array that I use to reference the charts. This is what I am struggling with. This is my current attempt to add the existing chart to the variant array.
charts(graphIndex) = Worksheets(activeSheetName).ChartObjects("chart name").Chart
When I run the code I am getting a "Run-time error '438': Object doesn't support property or method."
Hopefully I provided enough context, but any help on this would be greatly appreciated. This feels like it should be fairly easy, but I couldn't find any information online.
I am just guessing that in your code if you had the Set word it would have worked (However, I am not seeing the whole code, thus not sure).
This works, if you make sure to have 3 charts named "Diagramm 1", "Diagramm 2" and "Diagramm 3" on the first worksheet:
Option Explicit
Sub TestMe()
Dim cht2 As Chart
Dim varArray As Variant
With Worksheets(1)
Set cht2 = .ChartObjects("Diagramm 2").Chart
varArray = Array(.ChartObjects("Diagramm 1").Chart, cht2)
ReDim Preserve varArray(2)
Set varArray(2) = .ChartObjects("Diagramm 3").Chart
Dim cnt As Long
For cnt = LBound(varArray) To UBound(varArray)
Debug.Print varArray(cnt).Name
Next cnt
End With
End Sub
The Reedim Preserve increases the array units with one additional, while it keeps what it already has. Thus, at the end this is what we have in the locals:

PivotCache Refresh from Access

I am automating some Excel file creation from Access. I need help with dynamically resetting the pivotcache for all the pivot tables. The first set of code is me testing working code in Excel. Now I want to translate this so that it runs from Access module.
Sub Update_PTSource()
With Sheets("Pivot")
.PivotTables(1).ChangePivotCache ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("Data").Range("data"))
End With
End Sub
Function pivot_refresh_test()
Dim pt As Variant
Dim wb, ws As Object
Dim strWBName As String
Dim strTabName As String
strWBName = "C:\Users\...\Packaged SKU.xlsb"
strTabName = "Pivot"
Set wb = GetObject(strWBName)
For Each pt In wb.Sheets(strTabName).Pivottables
pt.ChangePivotCache wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wb.Sheets("Data").Range("data"))
pt.RefreshTable
Next pt
End Function
I'm getting error on pt.ChangePivotCache line with error
invalid procedure call or argument
As far as I can see, you've only made one simple error:
xlDatabase is an Excel enum, and since you're using late bindings, you don't have access to it. You can use it's integer value, 1, instead:
For Each pt In wb.Sheets(strTabName).Pivottables
pt.ChangePivotCache wb.PivotCaches.Create(SourceType:=1, SourceData:=wb.Sheets("Data").Range("data"))
pt.RefreshTable
Next pt
I'm anal about using the least code possible when designing solutions so I found a much easier method to what I wanted to do.
My task was to update and refresh the source data of all my pivot tables. There was one source, multiple pivot tables. I created a dynamic named range for my source for this purpose in my template Excel book that Access was writing into. I never save over the template I just used saveas vba to create the filled copy.
However, since I had created a named range and am modifying always the same template file with Access, I don't need to write a program to change my pivotcache. I can just use 'Change Data Source' in Excel ribbon. The vba code gets much easier. It is just a variation of: ThisWorkbook.RefreshAll. No code loops required!
The whole power of my strategy is the formula that creates my named range. =Data!$A$5:OFFSET(Data!$A$5,COUNTA(Data!$A:$A)-1,52). You just set the first cell of your data, and set how many columns there are for your fields, the rows are automatically adjusted.
I hope this little rant help whoever navigates here. I've been searching a lot for good dynamic pivot table automation but most of the internet has crap info on this.

Excel 2016 VBA: Set Source Data for a Chart to a Named Table

The title is pretty self-explanatory.
I have a named table, Table_Unit_2_Data, which I would like to set as the source data for a chart that will be created using VBA.
During the recording of a macro I selected the entirety of the table, and inserted a chart. This is the code that I got (Build is the name of the Sheet):
Sub Test()
Range("Table_Unit_2_Data[#All]").Select
ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmoothNoMarkers).Select
ActiveChart.SetSourceData Source:= Range("Build!$Y$1:$AD$2")
End Sub
Well, for one thing, as you can see, a specific $A$1 range is passed into the SetSoureData. This will not work because the range of Table_Unit_2_Data will change.
I attempted this:
With Sheet2.Shapes.AddChart2(240, xlXYScatterSmoothNoMarkers)
.Chart.SetSourceData (Sheet2.Range("Table_Unit_2_Data[#All]"))
End With
But then I get the error "Object Required".
I can't seem to phrase my search queries in such a way as to find relevant answers to this specific question on the internet so I apologize for asking what is likely a redundant question. If someone could help me with this problem I would be greatly appreciative and if anyone has a good article or source online for information regarding the nuances of chart creation within VBA that would also be very helpful.
Thank you.
In addition to what Domenic said (which is correct + would cause the "Object Required" error), your code doesn't make it clear what "Sheet2" is, except that it's the codename of some sheet. From the recorded macro, I can infer that the actual table is on a sheet called "Build", so another possibility to consider is that Sheet2 isn't actually the codename of Sheets("Build"). Again, I can't actually tell from the code provided.
While I do like using sheet codenames, I'd strongly recommend against using them if you're not going to make the names descriptive.
FWIW, there's another way to reference table ranges that's a little more flexible, especially if you're going to be referring to the table elsewhere in the code. Just make a ListObject variable:
Dim UnitTable2 As ListObject
Set UnitTable2 = Sheets("Build").ListObjects("Table_Unit_2_Data")
And you'll be able to reference any part of the table really easily:
Dim rng As Range
'Reference the whole table, including headers:
Set rng = UnitTable2.Range
'Reference just the table data (no headers):
Set rng = UnitTable2.DataBodyRange
'Reference just the data in a single column:
Set rng = UnitTable2.ListColumns("Col1").DataBodyRange
'Reference the headers only
Set rng = UnitTable2.HeaderRowRange

Counting Chart series from a worksheet [by name]

I have searched through the forums and I cant find an exact solution to my problem. I am somewhat familiar with vba and coding in general but I am still very new to the VBA syntax. I keep getting errors along the times of syntax error, object not in range, etc. I want to get away from selection based actions and I want to call specific charts from sheets to count the amount of data series within.
It seems so simple and at this point im just frustrated I havent been able to actually debug it. I have tried a lot of different combinations and have been Googling all morning and all I get is new and different error messages. So I figured one of you may have a quicker solution than my tinkering. Any help would be super helpful, thanks!
Dim SheetName As String
Dim SC2 As Long
SheetName = ActiveSheet.Name 'assign the name of the active sheet to the variable
'Count # of series in chart to find # of loops required
ActiveWorkbooks.Sheets(Volume CT).ChartObjects(1).Chart.SeriesCollection.Count
'*^^^THIS IS WHERE THE ERROR OCCURS*
'Debug.Print ThisWorkbook.Sheets("Time CT").ChartObjects(1).Chart.SeriesCollection.Count
'Debug.Print ThisWorkbook.Sheets("Temp CT").ChartObjects(1).Chart.SeriesCollection.Count
Dim SC2 As Long
'chartobject method (chart is housed in a regular worksheet)
SC2 = ActiveWorkbook.Sheets("Volume CT").ChartObjects(1).Chart.SeriesCollection.Count
'if the chart is on a chart sheet:
SC2 = ActiveWorkbook.Sheets("Volume CT").SeriesCollection.Count

Accessing Pivot tables from another Sheet in VBA

Very novice user here, just getting my feet wet. Please excuse this if it's an idiotic question - I'm quite sure what I'm doing yet.
I'm creating a userform with VBA and Excel. I've been successful in learning how to pull information from a pivot table so far, but I've run into a hitch.
When run my userform from another sheet it can't find the pivot table. Here's the code I'm using.
Set PT = ActiveSheet.PivotTables(1)
Works perfectly when I'm one that sheet, but I envision a scenario where I have multiple pivots on different sheets and will want to call info and cross-reference the data.
I thought maybe Set PT = ActiveWorkbook.PivotTables(1) would work, but of course it doesn't. Obviously I don't yet quite understand how to use a pivot table variable.
Does anyone know how I might go about doing this? Thanks so much.
If you open UserForm, workbook with UserForm open will be the active one. If I understand correctly, you want to refer to 1st object of PivotTables collection on a different sheet. To do so, define path of the file with pivot table, example below:
Dim path as string
Dim wbk as workbook
Dim PT As PivotTable
path= "C:\folder1\folder2\yourfile.extension"
set wbk = workbooks.open(path)
Set PT = wbk.worksheets("Sheet1").PivotTables(1)
'do your actions, save the file if you want to keep changes
wbk.close
set wbk = nothing
Alternatively work on all Pivot Tables in your worksheet, instead of:
Set PT = wbk.worksheets("Sheet1").PivotTables(1)
You can use a loop through collection, this example refreshes tables:
For Each PT In wbk.worksheets("Sheet1").PivotTables
PT.RefreshTable
Next PT