Excel: How can I add custom gridline to a chart? - excel

How can I add a custom horizontal line that has a label and it is at the exact same level as the first column in the chart (see the screenshot below).
Can this be done in VBA?

This could be done in VBA, or it could be done without VBA:
http://peltiertech.com/Excel/Charts/AddLineHorzSeries.html
This method involves creating a secondary Y-axis, and plotting another series of data in a "line" on the second axis.
This is a fairly clean solution.
Otherwise with VBA you would need add a shape/line to the chart (important to add it to the chartObject and not to the Worksheet).
Then compute the height of points and make the line's .Left = the chart's .PlotArea.Left and make the line's .Width = to the chart's .PlotArea.Width. Then set the line's .Top value based on the chart's .PlotArea.Height minus the "height" you calculated for the point.

using vba, you can add a new series:
With ActiveChart.SeriesCollection.NewSeries
.Values = "={6.9,6.9,6.9,6.9}"
'create string beforehand if number and values are unknown
.ChartType = xlLine
'and whatever other formatting is needed
End With
not using VBA, you can add a new column to the data, and put all of it equal to the first item, using =$B$2 in each cell to add the line to the graph

Related

Hide/add legend to graph with conditions

I have 2 columns of data for my chart, but the second one is optional (with an IF formula).
I want the legend to only show the relevant series.
Because the legend is visible even if there is no data for the second column, I wrote this in the cell for the series name:
=IF(…………;"blabla";"")
Now the legend has no label and only the (yellow dashed) line appears:
How can I hide both the label and the line in this legend if the series has no data?
You can use VBA to realize this.
in Excel 2013 onward model
you can use Chart.FullSeriesCollection to select your series and toggle its Isfiltered properties
Like
If.....Then
ChartObjects("xxxx").Chart.FullSeriesCollection(2).IsFiltered = True
Else
ChartObjects("xxxx").Chart.FullSeriesCollection(2).IsFiltered = False
End if
If you are using old excel, like excel 2007, excel 2010.. you should only use Chart.legend.legendEntries(2).Delete to get rid of the legend. if you wanna toggle it back, you should use chart.hasLegend = false, Chart.hasLegend = true to make it back

Various transparent step in a line in a chart

I am using VBA with Excel 2013. I am developing a Macro with a chart, inside the chart there is a line made with a serie if points. I need apply a transparency shape to the steps between 2 point.
example
1 to 2 solid
2 to 3 transparent
3 to 4 solid
With .transparency = 0 and 1 the shape is applied to the whole line. I tryed to apply .trasnparency various time but it is applied to the whole line.
How do I apply transparency to have the behauvior described above?
The easiest way to get a gap is to insert a blank row between segments you want to be visible. In the top view below the data range is continuous, and so is the chart. In the bottom view, I've inserted blank rows between the X-Y values for the horizontal segments, and the chart rewards me with gaps in the plot, so the verticals don't show up.
You can't get these gaps if your code is inserting arrays into the chart series source data, but you can use code like this to make them disappear (by using No Line instead of Transparency, personal preference):
Sub TransparentVerticals()
Dim srs As Series
Dim iPt As Long
Set srs = ActiveChart.SeriesCollection(1)
For iPt = 1 To srs.Points.Count Step 2
With srs.Points(iPt)
.Format.Line.Visible = msoFalse
End With
Next
End Sub

excel macros - line chart loses year axis values and chart title

I am recording a macro using Excel 2013 to create a line chart.
I have one column with years and an adjacent column with population values. The column headings are "Year" and "Population" respectively.
The line chart looks good.
When I run the macro, the chart title (Population) is striped out. Additionally the year values (x axis) are replaced with a number series, 1 . . . onwards
How do I have the macro retain the year values and the chart title (Population)?
Thanks!
This is my recorded Macro
Range("A1:B29").Select
ActiveWindow.WindowState = xlMaximized
ActiveSheet.Shapes.AddChart2(227, xlLineMarkers).Select
ActiveChart.SetSourceData Source:=Range("compilation!$A$1:$B$29")
This is an example of what I want the final graph to look like when I run the macro.
Add the following line to your last line of your macro
ActiveChart.FullSeriesCollection(1).XValues = "=compilation!$A$2:$A$29"
That should get you your year back along the bottom.
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Select
Selection.Caption = "=compilation!R1C2"
That will set your Title for you. However you still need your Primary Horizontal Title so why dont we throw in this tid bit of random code:
ActiveChart.Axes(xlCategory).Select
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
Selection.Caption = "=compilation!R1C1"
now the only outstanding issue is if you are generating 1 or 2 lines in your graph.
To get rid of the second line (technically the first since its really series 1) we have two choices.
Choice 1 is to select it with the code and delete it. I am going to opt for choice 2 though. Choice 2 is to never add it in the first place!
So to start with eliminate your first line of your Macro. When the graph is initially created, it will be created as a blank slate as there is no preselected data. So what we need to do is change 1 lettre in the line of your macro where you define the Source. (4th line of your posted code) and we are going to change the starting cell reference from $A$1 to $B$1. If the graph only has one column of data to work with for points then there can only be one series. So that line will look like the following in the end:
ActiveChart.SetSourceData Source:=Range("compilation!$B$1:$B$29")

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/

How to plot chart values outside axis maximum?

In previous versions of Excel there was a registry entry that you could create to allow Excel to display values/labels that would be positioned outside the axis min/max using QFE_Bonn dword=1. This is what I have used for Excel 2003: Plot lines that contain labels disappear ...)
I have not been able to find a similar patch or native functionality in Excel 2010 (Office Pro Plus). Any ideas how this can be accomplished, or did MS remove this functionality altogether?
Here are screenshots of examples in Excel 2003. I create a series of data which uniformly exceeds the y-axis maximum. This series' color fill has been removed already
To finish the look, remove the series' border so that it appears invisible. Then replace the series' value labels with the relevant data.
There is a workaround using the DataLabels.Left property which positions the DataLabel relative to the ChartArea.
Here is an example VB solution:
sub FakeLabels()
Dim sF As Double
Dim lOff As Double
Dim p As Double
ActiveSheet.ChartObjects(1).Activate
With ActiveChart
For sF = 1 To .SeriesCollection.Count
If .SeriesCollection(sF).Name = "FakeSeries" Then
'Define the lOff variable by adding 100, or some other value
lOff = .SeriesCollection(sF).Points(1).DataLabel.Left + 100
For p = 1 To .SeriesCollection(sF).Points.Count
.SeriesCollection(sF).Points(p).DataLabel.Left = lOff
Next p
End If
Next sF
End With
It yields the same results, the only new requirement is to keep the values for the "dummy" series within the axis min/max values for the chart.
A pleasant surprise is that re-sizing the chart doesn’t appear to affect the relative placement of the labels.
UPDATED 9-25-2013
I have used the "textbox" approach since first asking this question. But it is extremely clunky to manage the interplay between the labels' position and the textbox positions, their relative position of the PlotArea i.e., when to use .InsideWidth vs. .Width or .InsideLeft vs. .Left and whether there needs to be any sort of hedonic "adjustments" to the points values, as always seem to be the case, they are never quite perfectly aligned.
While perusing the PPT object model reference for some other chart-related inquiries, I stumbled upon this property which appears to replicate the functionality of the previous hotfix/registry hack.
.ShowDataLabelsOverMaximum

Resources