Extract data from a pivot table using VBA - excel

My project is to use Excel data to make some PowerPoint Slides. I need to calculate some values and get some string from PivotTable :
Scheme of the Excel and the data to be extracted
Values are not fixed for steps and substeps.
nbSteps = int --> 1 slide for each step
nbSubStep = int --> 1 rectangular shape for each substep
StepName = string --> Title of Step's slide
SubStepName = string --> Text into rectangular shape
for each Step in Steps
StepName = Step.Name
'--- PowerPoint VBA stuff ---'
for each Sub in SubStep
SubStepName = SubStep.Name
'--- PowerPoint VBA stuff ---'
Next
Next
This is not actual code, but just the idea of what I want to do
The result if it helps :
powerpoint result
Thank you for your help.
I tried several kinds of manipulation with GetPivotData() but also with GetData() without success.
For the creation of the PowerPoint, I don't have too many problems for the moment. It is the manipulation of the pivot table that is holding me back.
Ps: As this is my first post, feel free to tell me what I should change in my question!

Related

When I add a chart into excel using VBA sometimes it becomes a pivot chart and causes errors

I have a pivot table with 3 values in it. Volume Processed, Volume Billed, and Billed Revenue. VB is always a subset of VP, and BR is often in the 100,000s compared to VB and VP which are usually less than 1,000. Additionally, there are over 1000 data points in my test data. I've only loaded in 2 months, and when it's done it has to be able to quickly handle an entire year. So Pivot Charts won't work. BR is a currency and VB and VP are just numbers. The chart I want is to show (VP-VB) stacked on top of VB where the height of VB = BR and the height of (VP-VB)+VB = (VP*BR)/VB. I also try to use a smaller amount of data points. If all the IDs are showing, that's over 1000 columns on the graph, it's much easier to see them group by buildings until you use a slicer to bring down the number of IDs to something more manageable.
My solution is to use VBA to make my own graph, scrape the data from the pivot table, figure out what graph the user wants to see, and then build it from scratch.
The problem is that sometimes the chart preloads with a pivot chart and then when I try to add in my data it throws a Run-time error. I am having trouble even creating the error because it doesn't always happen.
Dim MyChart as Object
Dim chtrng as Range
Dim srs as Series
Dim arrayvalues() as Double
Dim areayXvalues() as Variant
Set chtrng = Sheets("Pivot").Range("H30:T50")
Set MyChart = ThisWorkbook.Sheets("Pivot").ChartObjects.Add(Left:=chtrng.left,Width:=chtrng.width,Top:=chtrng.Top,Height:=chrrng.Height)
With MyChart.Chart
.ChartType = xlColumnStacked
.Has title = True
.ChartTitle.text = GraphName(0)
For j = 1 to 2
For I = 1 to GraphList.Count
Arrayvalues(i-1) = GraphList(I)(j)
Next I
Set srs = .Series collection.NewSeries
With srs
.Xvalues = areayXvalues
.Values = areayvalues
.Name = GraphName(j)
End With
Next j
End With
"Set srs" is where the error comes in. This is also the first pass of j. When I step through the code, the times that it works, at "Set MyChart" the graph is empty, but the times it doesn't work, the graph has a pivot chart inside. At the beginning of the actual code I delete all charts on the sheet.
Every scenario I try, with different data displayed in the pivot table has done both. I can't figure out what is even causing the issue.
I've tried making sure MyChart is set to nothing. I have code that calls the makegraph sub when the pivot table updates, I created a on/off switch for that. I've tried to disconnect all of my data scraping from the pivot table so that by the time I start on the graph none of my variables are attached to the table.
Most of the time the graph works exactly as expected, but every now and then it gives me a Run-time error '1004' on "Set srs"

VBA Listbox displaying error symbol with currency formatting

I am using a ListBox in a UserForm to display the data from a Table in my worksheets. All the data is correctly formatted in the table but in the ListBox, the currency is being displayed with an "error symbol" which should simply be a space (as per the french standard for currency formatting) and looks like the following :
I won't add the code for the UserForm since I am only having issues when inserting the data into the ListBox. However, below is the code responsible for populating said ListBox where msOperationTable is of type ListObject :
TableEntries.ColumnCount = 6
TableEntries.ColumnHeads = True
TableEntries.ColumnWidths = "100; 140; 150; 85; 100; 70"
TableEntries.RowSource = msOperationTable.Parent.Name & "!" & msOperationTable.DataBodyRange.Address
I haven't been able to find any explanation as to why this happens and I am starting to wonder if there is anything that can be done to fix this.

From a selected line in a chart, filter a table or pivot table

I am facing a challenge. In a chart with multiple lines, I would like to able when I click on a line or mouse over a line to see the corresponding datapoint in the the table or pivot table...So basically, filtering a table based on the element i click or select on a chart with my mouse.
Do you think that it is achievable ? What would be the methodology ? Is there a VBA code for this ? I have seen examples, but they are working on the oppiste way; click or mouse over an observation and the line is highlighted...
Thanks in advance
saskap
This is really complicated, you have to customize the code for each chart, this example code can be a starting point:
Dim p As Series
Dim pc As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ch As ChartObject: Set ch = Me.ChartObjects("Chart 1")
With ch
Dim s As Series: Set s = Nothing
On Error Resume Next: Set s = .Chart.SeriesCollection(Target.Value): On Error GoTo 0
If Not p Is Nothing And Not p Is s Then
p.Format.Fill.ForeColor.RGB = pc
End If
If Not s Is Nothing Then
Set p = s
pc = s.Format.Fill.ForeColor.RGB
With s
s.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
End With
End If
End With
End Sub
The first two rows are global variables that store which Series
object was highlighted last time and what was its original color,
this is needed to restore the original color when a different cell is
selected. Unfortunately global variables in VBA loose their value when the project is reset (e.g. the Stop button is pressed or an error occurs), so it is possible that this code colors a bar and then cannot color it back. If important, these information may be stored in invisible Cells or Chart data but that complicates the code.
The next line means that this is an event handler, a function that is called in response to a certain event, in this case when the selection changes on a certain worksheet (the one on which you insert this - you have to insert this into a worksheet module not a standard code module).
Next we look up the chart based on its name and assign it to a variable, which is of type ChartObject, so early binding will allows us to depend on the support of intellisense (if you type a . it shows members of interfaces).
Then we look up the Series inside the chart based on the name found in the newly selected cell's contents. Since we don't know if the new cell will have a valid name, we have to protect this line with disabling error handling and checking later if the s has a non-nothing value. - This part depends largly on the type of chart and how it represents data, it is possible that you will have to select data based on Series::XValues.
We check if there is a saved value for a previously highlighted bar and if it is different from the current selection, restore its original color.
Finally if the looking up the Series earlier was successful then s is non-null and we save the color of the current bar and highlight it with red fill.

Adding several elements to a listbox menu in vba

I am trying to create a menu with list boxes in order to be able to select a number of customers from a list in an excel sheet. There are two list boxes, one with all the (default) data and one with the selected customers.
There is no problem adding one customer but when I add a second customer the graphic interface shows nothing, but after some debugging, the SelectedCustomers.RowSource still have the two rows in its data:
?SelectedCustomers.RowSource
$8:$8,$11:$11
This would have me believe there is some error with how I save the data or some limitations to Excel that I am not aware of. This is the code I use to save the data:
Private Sub CommandButton5_Click()
Dim temp As Range
For i = 0 To DefCustomers.ListCount - 1
If DefCustomers.Selected(i) = True Then
If temp Is Nothing Then
Set temp = Range(Rows(i + 4).Address)
Else
Set temp = Application.Union(temp, Range(Rows(i + 4).Address))
End If
End If
Next i
SelectedCustomers.RowSource = temp.Address
End Sub
Has someone experienced this before or know what the problem might be?
Instead of RowSource use AddItem method:
For i = 0 To DefCustomers.ListCount - 1
If DefCustomers.Selected(i) Then
SelectedCustomers.AddItem DefCustomers.Selected(i)
End If
Next i
There are known issues with ListBox.RowSource property in Excel VBA.
[EDIT]
After the discussion...
No matter of number of columns, you can copy rows from source sheet into another sheet, then bind SelectedCustomers listbox to that data

Colouring an Excel stacked bar chart's points in relation to a value assigned in a table

I am trying to create a roadmap/timeline in Excel 2010 using a stacked bar chart. I have provided a link below to an image which should explain my intentions with the chart. I wish to present different events in the chart and they should be drawn in relation to their duration. The longer the event is, the longer its respective bar is.
I have managed to build a macro that creates a chart of my liking. However, I wish to add another functionality to it. As it can be seen from the picture below, there is a column called 'Type' in the original table. It stands for the status of the event, whether it is completed, canceled or being planned. My aim is to have the chart represent this data by coloring the bars either red (if canceled), green(if completed) or blue (if planned) depending on what value the particular event in question has in its Type row.
Below is the code behind the macro that the button 'Create a New Event View' uses. I would like to know how to implement the coloring, preferably in this very same macro so that the user only needs to click the button.
Sub CreateEventTable()
Dim timespan_start As Date
Dim timespan_end As Date
timespan_start = Application.InputBox("Type start date:")
timespan_end = Application.InputBox("Type end date:")
ActiveSheet.Shapes.AddChart(xlBarStacked, Range("E2").Left, Range("E2").Top).Select
With ActiveChart
.SetSourceData Source:=Range("$A$1:$B$12, $D$1:$D$12"), PlotBy:=xlColumns
.SeriesCollection(1).Values = Range("B2:B12")
.SeriesCollection(1).XValues = Range("A2:A12")
.SetElement msoElementLegendNone
.ChartGroups(1).GapWidth = 31
.SeriesCollection(2).ApplyDataLabels
.SeriesCollection(2).DataLabels.ShowCategoryName = True
.SeriesCollection(2).DataLabels.ShowValue = False
.SeriesCollection(1).Format.Fill.Visible = msoFalse
.Axes(xlValue).MinimumScale = timespan_start
.Axes(xlValue).MaximumScale = timespan_end
End With
End Sub
Here is the link to the image which hopefully explains the overall structure:
http://i.imgur.com/XzPoMiY.jpg
I appreciate your invaluable help! I am happy to provide more details if deemed necessary.
Best solution here is not VBA. You'll need to create multiple series for your chart, have them overlapped, and use formulas to populate if they meet the criteria. Changes automatically, and very easy to maintain.
As Skip Intro said, Jon Peltier is the chart master.
This link will get you started in the right direction.
http://peltiertech.com/WordPress/conditional-formatting-of-excel-charts/

Resources