Turning the visibility of chart series on/off using excel Macros/vba - vba

I am making a line graph (chart) in Excel with several data series being plotted onto the same chart.
I need to create a macro/VBA solution that can turn the visibilty of these series on/off via the pressing of a button (or tick box etc)
Similar to this picture (manually done through the excel menu system)
I have tried to look through all the member vars/methods on
https://msdn.microsoft.com/EN-US/library/office/ff837379.aspx
but haven't had much luck.
I have tried playing around with bits like
Charts("Chart1").SeriesCollection(1)
and
Worksheets("Graphical Data").ChartObjects(1)
but I can neither get the chart object ( I get a subscript out of range error) nor able to find any method that would allow me to turn on/off the visibility of individual series.
Any Ideas?

Whenever I don't know how to do something like this, I turn on the macro recorder.
I had a chart with four series, and I used the filter function in Excel 2013 to hide and show the second series, while the macro recorder was running.
Here's the relevant code:
ActiveChart.FullSeriesCollection(2).IsFiltered = True
' series 2 is now hidden
ActiveChart.FullSeriesCollection(2).IsFiltered = False
' series 2 is now visible
The series type (line or column) does not matter, this works for any of them.

I believe the property you are looking for is the SeriesCollection.Format.Line.Visible property. I quickly created an Excel workbook and added a simple data set (just 1-10) and added a line graph "Chart 2" to the sheet Sheet1.
This code turned the visibility of the line off:
Option Explicit
Private Sub Test()
Dim cht As Chart
Dim ser As Series
'Retrieve our chart and seriescollection objects'
Set cht = Worksheets("Sheet1").ChartObjects("Chart 2").Chart
Set ser = cht.SeriesCollection(1)
'Set the first series line to be hidden'
With ser.Format.Line
.Visible = msoFalse
End With
End Sub
And likewise, setting the ser.Format.Line.Visible property to msoTrue made the line visible again.
As for retrieving the chart itself I had to first activate it, then set my cht variable to the ActiveChart. To view the name of your chart, select it and look in the name box (near where you would enter the cell value / formula).
Update
When using the method above, the series name remains in the legend box. I couldn't find a visibility property for the SeriesCollection in the legend, however one workaround is to simply re-name the series as an empty string (this will make the series disappear from the legend) and then rename the series when you want to show it.
This code below will toggle the visibility of the line and series name in the legend.
Option Explicit
Private Sub Test()
Dim cht As Chart
Dim ser As Series
'Retrieve our chart and seriescollection objects'
Set cht = Worksheets("Sheet1").ChartObjects("Chart 1").Chart
Set ser = cht.SeriesCollection(1)
'Set the first series line to be hidden'
With ser.Format.Line
If .Visible = msoTrue Then
.Visible = msoFalse
ser.Name = vbNullString
Else
.Visible = msoTrue
ser.Name = "Series 1"
End If
End With
End Sub
And, whenever you use .Format.Line.Visible = msoTrue just remember to set ser.Name back to whatever the name for your series is.

There is a simple way to on & off the visibility of the series: using filter on your source data.
May it help you easily as follows.
You can insert a new Window. Setone of them to source data sheet and the other window to Chart sheet. Then arrange the two windows to see both at the same time. Now if you filter the series you like on the source data sheet simultaneously you will see the series you desired on the other sheet.

Related

Creating a chart in powerpoint using VBA only without embedded excel data

I am working on a personal powerpoint project and I thought it would be cool to use activex in the powerpoint to make the slides a bit more interactive. I have some activex boxes where you can set a population and an annual growth rate and the final step would be for me to plot the 5 year projection data i am getting on a line graph. I have tried it using excel based VBA but most solutions seem to require pulling data from a sheet so won't work in powerpoint.
I have also tried the following code to build a chart skipping the need for a worksheet but to no avail as I get a runtime error 424: Object required error:
Sub AddChart()
Dim cht As Chart
Dim ser As Series
Set cht = Charts.Add
cht.ChartType = xlColumnClustered
Set ser = cht.SeriesCollection.NewSeries
ser.XValues = Array(1, 3, 5, 7, 9)
ser.Values = Array(2.4, 3.2, 5.7, 12.67)
End Sub
Any solutions in mind or am I flogging a dead horse here?
Thanks!
Powerpoint doesn't have Charts.Add, but Shapes.AddChart2 or .AddChart
Something like this should get you going:
Sub AddChart()
Dim cht As Chart
Dim ser As Series
Set cht = ActivePresentation.Slides(1).Shapes.AddChart(-1, xlColumnClustered).Chart
Set ser = cht.SeriesCollection.NewSeries
ser.XValues = Array(1, 3, 5, 7, 9)
ser.Values = Array(2.4, 3.2, 5.7, 12.67)
End Sub
I know this is an old thread but in case someone stumbles on it like I did - you can paste an empty chart on a Master Layout and then copy it to any slide you need it on, that way Excel never launches to 'create' the chart object, although it is still 'embedded'.
If you create a special layout for it, just be sure to include a Title or some other placeholder because slides with no placeholders get helpfully removed/left behind by PowerPoint during certain operations - such as copying a slide into a new presentation and selecting 'Keep Source Formatting'.

Getting a series trend line equation to a shape text box

I'm attempting to get the trend line equation from the first series in my chart to a shape text box placed elsewhere on the worksheet - however, I can only get the textbox to populate correctly when I'm stepping through the code line by line - during run-time it has no effect:
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value
ThisWorkbook.Worksheets("MyDataSheet").Shapes(slopetextboxes(k)).TextFrame.Characters.Text = srs.Trendlines(1).DataLabel.Text
srs.Trendlines(1).DisplayEquation = False 'Turn it back off
Exit For
Next srs
k = k + 1 ' for the slope textboxes
Next chtObj
Note that slopetextboxes is an array containing the names of ~6 shape text boxes.
As far as I know there's no way to get the trend line data label without stopping to display it. I've tried storing it in a string first, DoEvents, and turning Application.ScreenUpdating back on, all to no avail. I'm stumped here.
EDIT: It appears that by placing DoEvents after .DisplayEquation = True I'm able to have some of my shapes populate correctly, but not all. Still appears to be some kind of run-time issue.
BOUNTY EDIT: I've moved ahead to grab the slopes with a formula ran into the data itself, but I still don't understand why I can't grab the chart's .DataLabel.Text during run-time. I can grab it when stepping through, not during run-time. It appears to just take the PREVIOUS series slope and place it in the shape (or a cell, it doesn't even matter where the destination is). DoEvents placed in different spots yields different outcomes, so something must be going on.
Updated with better understanding of the bug. This works for me in excel 2016 with multiple changes to the source data (and therefore the slope)
I tried myChart.refresh - didnt work. I tried deleting and then re-adding the entire trendline, also didnt work.
This works for everything but the first case. First case needs to be hit twice. Same as for .select
If you try and delete trendline even after assigning its text to textbox, this wont work
Option Explicit
Sub main()
Dim ws As Worksheet
Dim txtbox As OLEObject
Dim chartObject As chartObject
Dim myChart As chart
Dim myChartSeriesCol As SeriesCollection
Dim myChartSeries As Series
Dim myChartTrendLines As Trendlines
Dim myTrendLine As Trendline
Set ws = Sheets("MyDataSheet")
Set txtbox = ws.OLEObjects("TextBox1")
For Each chartObject In ws.ChartObjects
Set myChart = chartObject.chart
Set myChartSeriesCol = myChart.SeriesCollection
Set myChartSeries = myChartSeriesCol(1)
Set myChartTrendLines = myChartSeries.Trendlines
With myChartTrendLines
If .Count = 0 Then
.Add
End If
End With
Set myTrendLine = myChartTrendLines.Item(1)
With myTrendLine
.DisplayEquation = True
txtbox.Object.Text = .DataLabel.Text
End With
Next chartObject
End Sub
Here's my code that seems to definitely work when just pressing F5:
Basically, I store the text in a collection, then iterate through all of the textboxes to add the text to the textboxes. If this wasn't precisely what you were asking for, then I hope this helps in any way.
Sub getEqus()
Dim ws As Worksheet
Dim cht As Chart
Dim srs As Variant
Dim k As Long
Dim i As Long
Dim equs As New Collection
Dim shp As Shape
Dim slopetextboxes As New Collection
Set ws = Excel.Application.ThisWorkbook.Worksheets(1)
'part of the problem seemed to be how you were defining your shape objects
slopetextboxes.Add ws.Shapes.Range("TextBox 4")
slopetextboxes.Add ws.Shapes.Range("TextBox 5")
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value
equs.Add srs.Trendlines(1).DataLabel.Text
srs.Trendlines(1).DisplayEquation = False 'Turn it back off
Next srs
Next chtObj
For i = 1 To slopetextboxes.Count
'test output i was trying
ws.Cells(i + 1, 7).Value = equs(i)
slopetextboxes(i).TextFrame.Characters.Text = equs(i)
Next
End Sub
Pictures of what the output looks like when i just press the button
Good luck!
This worked for me - I loop through multiple charts on Sheet1, toggling DisplayEquation and then writing the equation to a textbox/shape on the different worksheet. I used TextFrame2.TextRange but TextFrame worked as well, if you prefer that. I wrote to both a regular text box, as well as a shape, which was probably overkill as the syntax is the same for both.
This gets the trendline equation from the first Series - it sounded like you didn't want to loop through all the Series in the SeriesCollection.
Sub ExtractEquations()
Dim chtObj As ChartObject
Dim slopeTextBoxes() As Variant
Dim slopeShapes() As Variant
Dim i As Integer
slopeTextBoxes = Array("TextBox 1", "TextBox 2", "TextBox 3")
slopeShapes = Array("Rectangle 6", "Rectangle 7", "Rectangle 8")
For Each chtObj In ThisWorkbook.Sheets("Sheet1").ChartObjects
With chtObj.Chart.SeriesCollection(1).Trendlines(1)
.DisplayEquation = True
ThisWorkbook.Sheets("MyDataSheet").Shapes(slopeTextBoxes(i)).TextFrame2.TextRange.Characters.Text = .DataLabel.Text
ThisWorkbook.Sheets("MyDataSheet").Shapes(slopeShapes(i)).TextFrame2.TextRange.Characters.Text = .DataLabel.Text
.DisplayEquation = False
i = i + 1
End With
Next chtObj
End Sub
I've written this off as a bug - The only workaround was discovered by BrakNicku which is to Select the DataLabel before reading its Text property:
srs.Trendlines(1).DataLabel.Select
Not a sufficient solution (since this can cause some issues during run-time), but the only thing that works.
I had a similar issue running the code below and my solution was to run Application.ScreenUpdating = True between setting the trendline and querying the DataLabel. Note that screen updating was already enabled.
'Set trendline to the formal y = Ae^Bx
NewTrendline.Type = xlExponential
'Display the equation on the chart
NewTrendline.DisplayEquation = True
'Add the R^2 value to the chart
NewTrendline.DisplayRSquared = True
'Increse number of decimal places
NewTrendline.DataLabel.NumberFormat = "#,##0.000000000000000"
'Enable screen updating for the change in format to take effect otherwise FittedEquation = ""
Application.ScreenUpdating = True
'Get the text of the displated equation
FittedEquation = NewTrendline.DataLabel.Text
If it works when you step through, but not when it runs then it's an issue with timing and what Excel is doing in between steps. When you step through, it has time to figure things out and update the screen.
FYI, Application.Screenupdating = False doesn't work when stepping
through code. It gets set back to True wherever the code pauses.
When did you give it a chance to actually do the math and calculate the equation? The answer is that, you didn't; hence why you get the previous formula.
If you add a simple Application.Calculate (in the right spot) I think you'll find that it works just fine.
In addition, why should Excel waste time and update text to an object that isn't visible? The answer is, it shouldn't, and doesn't.
In the interest of minimizing the amount of times you want Excel to calculate, I'd suggest creating two loops.
The first one, to go through each chart and display the equations
Then force Excel to calculate the values
Followed by another loop to get the values and hide the equations again.
' Display the labels on all the Charts
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value
' I take issue with the next line
' Why are you creating a loop, just for the first series?
' I hope this is just left over from a real If condition that wan't included for simplicity
Exit For
Next srs
Next chtObj
Application.ScreenUpdating = True
Application.Calculate
Application.ScreenUpdating = False
' Get the Equation and hide the equations on the chart
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
ThisWorkbook.Worksheets("MyDataSheet").Shapes(slopetextboxes(k)).TextFrame.Characters.Text = srs.Trendlines(1).DataLabel.Text
srs.Trendlines(1).DisplayEquation = False 'Turn it back off
Exit For
Next srs
k = k + 1 ' for the slope textboxes
Next chtObj
Application.ScreenUpdating = True
Update:
I added a sample file based on your description of the issue. You can select 4 different options in an ActiveX ComboBox which copies values to the Y-Values of a chart. It shows the trend-line equation below, based on the formula & through copying the value from the chart into a Textbox shape.
Maybe 2016 is different, but it works perfectly in 2013. Try it out...
Shape Text Box Example.xlsm

How do I control my charts using check boxes?

Fore-warning, I am teaching myself VBA as I work on this project, so I apologize if my coding is cringe-inducing and makes no sense. I am currently working on an excel chart that graphs four different series of 15 different categories. I would like to be able to make each series hidden on the chart whenever I click the assigned checkbox. Right now I have the four checkboxes next to the graph, one for each series, "2015", "2016", "2017", and "2018". I right-clicked on the first checkbox, "2015", and selected Assign Macro. The macro-name was filled in for my, so I selected edit, and the coding module popped up. So far my code looks like this:
Sub CheckBox25_Click()
If Cell("Q30").Value = "False" Then
Chart.Series("2015").Hidden = True
Else:
Chart.Series("2015").Hidden = False
End If
End Sub
"Q30" is the cell I have linked to the checkbox to display the true/false value.
I am aware that "Chart.Series("2015").xxx is not the proper way to call on the sereis.
If someone could please tell me how to properly call on the series so I can hide it from the chart that would be greatly appreciated. I'm also not sure that ".hidden" is the correct identifier to use, if you could point me in the right direction for that too that would be great.
Currently I get the "sub or function not defined error" but I believe that is because of my incorrect coding.
Instead of turning visibility, the code below simply filters the Chart series, remember to amend the Sheet name and the Chart name too, then do the same for other Series:
Sub CheckBox25_Click()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
If ws.Cell("Q30").Value = "False" Then
ws.ChartObjects("Chart 1").Chart.FullSeriesCollection("2015").IsFiltered = True
Else
ws.ChartObjects("Chart 1").Chart.FullSeriesCollection("2015").IsFiltered = False
End If
End Sub

Referencing Charts By Name Only in PowerPoint VBA

I have been searching for hours to try to find the answer to this question, but to no avail, so I'm hoping I can find the answer here.
I want to create a variable that refers to a pre-existing chart in PowerPoint so I can start automating its data. I want to refer to the chart by its name to make things very easy, but no matter what I do I cannot seem to give PPT a satisfactory Chart address.
I have tried almost every possible variation of the below, but without success:
Dim chrtPP As PowerPoint.Chart
Set chrtPP = ActivePresentation.Slides(1).Shapes.Charts("Chart3")
Could someone please tell me what I'm doing wrong?
Thanks!
You need to reference the shape by name (a 'Shape" in PowerPoint is actually any object that is on a slide and can be a simple shape, textbox, table, chart, group, media clip etc.). If you're on PowerPoint 2010 and higher, press Alt+F10 to open the selection pane to find the name of the selected chart object. It may be a standard chart object or a chart within a placeholder object. You can then reference the chart as follows:
Option Explicit
Sub ChartStuff()
Dim oShp As Shape
Dim oCht As Chart
Set oShp = ActivePresentation.Slides(1).Shapes("Chart 3")
If oShp.HasChart Then
Set oCht = oShp.Chart
End If
' Do stuff with your chart
If oCht.HasTitle Then Debug.Print oCht.ChartTitle.Text
' Clean up
Set oShp = Nothing
Set oCht = Nothing
End Sub
The key in programming PowerPoint is to ignore the object name in the Object Model for 'Shape' as it's very misleading!

Inserting a chart and using data from different worksheets

I'm trying to insert a chart into a worksheet that would display information from 4 columns.
The x-axis has the dates and the y-axis would have a $ figure amount.
This is what I've gotten from recording a macro (which shows what I want at least):
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
ActiveChart.ChartArea.Select
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = "=""target"""
ActiveChart.SeriesCollection(1).XValues = "=MacroParty!$R$4:$R$55"
ActiveChart.SeriesCollection(1).Values = "=MacroParty!$S$4:$S$55"
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(2).Name = "=""current"""
ActiveChart.SeriesCollection(2).XValues = "=VA05NDump!$G$2:$G$833"
ActiveChart.SeriesCollection(2).Values = "=VA05NDump!$P$2:$P$833"
The problem is that this just plops a chart int he middle of the sheet and I'm looking to have it in a specific location.
I'm guessing there's a way nicer way of writing this but I am new to VBA and relying on the brute force method.
Any help would be greatly appreciated!
OK you can clean this up a bit. The macro recorder is great because it can help you see what you need to do, but it is little more than simply replicating key-strokes or mouse-clicks, and the point of programming in VBA should be to work directly with the objects -- much more efficiently than mimicking keystrokes.
I will show some examples of using variables to make your code more concise and hopefully easier to interpret. I'll comment it for you so you can see what I'm doing, and why.
Sub Test()
Dim cObj As Shape 'A Shape container for the Chart
Dim cht As Chart 'Variable will represent the chart
Dim srs As Series 'Variable will represent series
Set cObj = ActiveSheet.Shapes.AddChart '##cObj will refer to this shape
Set cht = cObj.Chart '## cht will refer to this chart
'(Now, the variable "cht" will refer to this specific chart until/unless
' you assign it to another chart.
'## Set the chart type:
cht.ChartType = xlXYScatterSmoothNoMarkers
'## To manipulate the chart's size and location you can use
' something like this to align it with a cell
' there are also Height, Top, Left, Width, etc.
cObj.Top = Range("A1").Top
cObj.Left = Range("A1").Left
'## To manipulate it's size, you can work with
' there are also Height, Top, Left, etc. properties, etc.
cObj.Width = 500
cObj.Height = 300
'## Manipulating the PlotArea, etc.
' there are also Height, Top, Left, etc. properties, etc.
cht.PlotArea.Width = 450
cht.PlotArea.Height = 250
'## Add series to the chart
Set srs = cht.SeriesCollection.NewSeries
srs.Name = "=""target"""
srs.XValues = "=MacroParty!$R$4:$R$55"
srs.Values = "=MacroParty!$S$4:$S$55"
'## "srs" will refer to SeriesCollection(1) until/unless you
' assign it to something else...
'... like now, we want to add another series,
' so we will just assign another NewSeries to the "srs" variable
' and work with the variable srs.
Set srs = cht.SeriesCollection.NewSeries
srs.Name = "=""current"""
srs.XValues = "=VA05NDump!$G$2:$G$833"
srs.Values = "=VA05NDump!$G$2:$G$833"
End Sub