Reinstate Excel chart default resizing behaviour using VBA - vba

I am looking for a way to reinstate the default/native resizing behaviour of a chart in Excel 2010 once it has been disabled (e.g. by manipulating the chart with VBA).
Now I haven't been able to find anything anywhere about the behaviour I have in mind, so I am going to assume that it needs detailed explanation.
Input and select random numerical data into 4-5 cells in Excel, and insert a new Clustered Columns chart. You need to see a the chart's plot area. Now select the chart, and get the PlotArea.Top value with the following line
ActiveChart.PlotArea.Top
If you haven't touched the chart, this should return a value of 7. Now use one of the chart's handlebars to resize the chart vertically, and use the same command line again.
activechart.plotarea.top
Notice how the value returned is still 7. Now set this property to 7 in VBA.
ActiveChart.PlotArea.Top = 7
Again, grab one of the handlebars, resize the chart vertically and get the .top property again using:
ActiveChart.PlotArea.Top
Notice how the value has now changed. It will be either smaller or greater than 7 depending on whetehr you decreased or increased the size of the chart.
Once any element of a chart has been moved either manually or with VBA code, it loses this "absolute position" property and begins moving inside the ChartArea whenever the chart is resized. While some elements can be reset using .SetElement, this does not work for the Plot Area. For example, the following command lines do not reinstate the behaviour I am describing.
ActiveChart.SetElement msoElementPlotAreaNone
ActiveChart.SetElement msoElementPlotAreaShow
I do a lot of automated resizing of charts with VBA, and having the plot area move around by itself makes it a lot harder to predict the effect of resizing the chart and leads to inconstant results.
So back to the question: does anyone know of a way to reinstate this default behaviour, either for the entire chart, or at least specifically for the PlotArea?
Thanks in advance to anyone who may help!
Vincent

I ran into this when I manually resized the plot area and then when the legend is moved it did not resize the plot area at all.
I had tried to save my chart as a template (right click save as template in Excel 2013) but this still had the plot area manually set.
Therefore I would recommend keeping the auto-size behavior before saving a template, since the only way I know to re-set the chart auto-sizing behavior after it has been manually modified is to use a macro
Here is the macro I used to reinstate the auto-sizing behavior
Sub Macro1()
'
' this selects the chart based on the chart name
ActiveSheet.ChartObjects("Chart 4").Activate
' this selects the plot area
ActiveChart.PlotArea.Select
' this clears any custom formatting such as borders or fill colors
ActiveChart.PlotArea.ClearFormats
' this resets the auto-sizing behavior after plot area manually re-sized
ActiveChart.PlotArea.Position = xlChartElementPositionAutomatic
End Sub
References
Why plot area does not expand after clearing series legend?
Excel Chart Plot Area Auto Size - ExcelBanter

Related

How to change data label width in an Excel chart with VBA?

I want to change a label width in Excel chart by VBA code:
set lbl = SERIES1. points(1).datalabel
msgbox lbl.width 'this is working
lbl.width = 40 ' compile error: wrong number of arguments or invalid property assignment
I can get the label width but cannot change it. What am I doing wrong?
AFAIK, the width of a chart data point label is not configurable. Even though the width can be retrieved with VBA, it's not possible to set or change it with a VBA command or property.
According to the documentation, the DataLabels.Width property is read only.
Returns the width, in points, of the object. Read-only.
Source
Excel chart labels remain stubbornly uncooperative and resist formatting attempts, be it with VBA or with the UI.
That's (unfortunately) just how Excel works.
Don't shoot the messenger.
If you want to make a difference, consider raising an idea at excel.uservoice.com
This works in Excel 2016, you'll just need to adjust the series collection and point numbers to fit your needs. ActiveChart.FullSeriesCollection(1).Points(1).DataLabel.Width = 363.314.

Excel Histogram - Distribution Line

I want to make a histogram in excel which is easy using data analytics toolbox. If I wanna make it automatic in vba I can use this post to get the bins automatically and then set the reference ranges.
Problem arises when I want to have the smoothed distribution line. If I change the chart type to scatterplot smooth line, it will connect the columns height to each other which will be like the blue line in this picture:
But what I really want is something like the purple line (i.e. a normal distribution overlaid on top of the histogram). This is not be desired if the data is skewed or generally have a different distribution. Is there anyway to make this overlay automatic in reference to distribution of the data? (Something like what R does) Preferably using macro, but any input would be great.
I added a Trendline to my chart (in red) and then formatted the Trendline as "Polynomial" and it achieved an effect similar to what you have.
Here's some code to achieve this programatically:
Sub AddPolynomialTrendline()
Dim chrt As Chart
Dim chrt_obj As ChartObject
Dim trend As Trendline
For Each chrt_obj In ActiveSheet.ChartObjects
If chrt_obj.Name = "Chart1" Then
With chrt_obj.Chart
'the number after xlPolynomial is the order, which can be from 2 to 6
Set trend = .SeriesCollection(1).Trendlines.Add(xlPolynomial, 6)
End With
End If
Next chrt_obj
End Sub
Hope this helps!

Trouble getting VBA Script to create desired chart

As shown in the image below, I have a chart (on the left) that I created manually. And I have the chart on the right which I created with the following VB Script:
Sub StackedBarChart()
'
' StackedBarChart Macro
'
'
Range(ActiveCell, Cells(ActiveCell.End(xlDown).Row, ActiveCell.End(xlToRight).Column)).Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnStacked
ActiveChart.PlotBy = xlColumns
ActiveChart.SetElement (msoElementDataLabelCenter)
ActiveChart.SeriesCollection("Total").Format.Fill.Visible = msoFalse
End Sub
Where I am falling short with my macro is the following areas:
I need to set just the "Total" data label to InsideBase
I need to rescale the y-axis. But, this needs to work for any data set. So, for example, taking the highest total value and adding $2.5 to it in order to make it a decent looking chart.
Automatically make sure that all of the Data Labels on the Legend appear. Right now, only 4-12 appear.
Thanks for your help!
With the
Range(ActiveCell, Cells(ActiveCell.End(xlDown).Row, ActiveCell.End(xlToRight).Column)).Select
you select the whole line including the totals. So on top of your stacked chart you have the total values again, so this doubles the high.
With (and here I am not quite sure)
ActiveChart.SeriesCollection("Total").Format.Fill.Visible = msoFalse
you just supress the display of the 'Total' stack. Just try to comment this line out, and I supose that you will get another element on top.
The best you probably can do is to redo the chart manually while recording a macro and checking the statements there.
For the legend you possibly need to increase the size of the display area.
The totals you can possibly dray an invisible stack with a 100% overly in the background. Then the values should be shown but no bar is displayed.

Customized report colors "snapping" to windows default colors

I have a chart in an Access 2010 report for which I am trying to set colors of different series dynamically. The user can use checkboxes to select series to chart, with the intent being that the series on the chart will take its color from the BackColor property of the checkbox's label.
The problem is that when I run my code to create the report, the colors used are not the ones on the corresponding labels. Instead it looks like they are "snapping" to the list of colors at the following link, referred to as "standard windows colours". List of standard windows colors in RGB and Long
For example:
With myChart.SeriesCollection(1)
.Interior.Color = RGB(195, 215, 155)
End With
Sets series 1 to a dark grey color, and debug.print myChart.SeriesCollection(1).Interior.Color returns 12632256, rather than 10213315 like it should. (Long color = Red + Green*256 + Blue*65536)
I have tried opening the chart object and defining the custom colors that I want to see on the palette for the chart, and setting the appropriate colors for the series manually. This works until I try to programatically change anything, at which point, all of the colors snap to the list I linked above.
Any ideas for how to dynamically set chart colors to custom values?
Managed to answer my own question. Manually customizing the palette in MS Graph was necessary, but from there, I need to reference the colors by their index on the palette (using .Interior.ColorIndex), rather than from their RGB or Long code. The index numbers for the palette are not in any logical order, but can be found in a file accessible from this site.
It's not quite as dynamic as I had hoped for, but this is definitely good enough for what I need to do.

Color Points (Bars) in Pivot Chart based on Row Labels (Axis Fields)

I'm trying to automate a process that so far I have been doing manually in Excel 2010. I create Pivot Charts often. One of the series on these charts is displayed as bars. I change the fill color of each bar based on one of the row labels of the pivot chart. For instance, if the row label = "GEO", I change the fill color of the bar to green.
I'm sure that it's possible to automate this process through VBA. Here's my code so far. When I run this macro, it stops at the first line of the If statement and gives this error. Compile error: Expected array. Can anyone give me some advice as to how to make this code work?
Sub By_Rig_PC_Coloring()
For i = 1 To ActiveChart.SeriesCollection(2).Points.Count
ActiveChart.SeriesCollection(2).Points(i).Select
If xlRowField("MFR") = "GEO" Then
Selection.Format.Fill.Forcolor.RGB = RGB(0, 176, 80)
End If
Next i
End Sub
As far as I know, you cannot access X axis labels associated with current Point. But this is a PIVOT chart, so you can use your pivot table to get the info you need.
Points are DataField's PivotItems, Series are ColumnFields and X labels are RowFields.
So SeriesCollection(2).Points(10) will be pvtYourPivotTable.ColumnFields(2).DataRange.Cells(10) (assuming that you have only one DataField, otherwise DataRange will be multi-column, and you'll have to adjust for that).
So once you have a cell in pivot table assosacietd with Point, the label will be located at Intersect(pvtYourPivotTable.RowFields("MFR").DataRange, pvtYourPivotTable.ColumnFields(2).DataRange.Cells(10).EntireRow. You can also use Offset or other method.
Here is another method of colouring chart bars based on X labels: Peltier Tech Blog without VBA.
Hope this helps.