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

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.

Related

Center Data Label over XY scatter with lines

I am in the process of creating the following chart:
But I need each data label to be centered over the line that gets created instead of the end point of the line. I have the following:
Set mypts = mysrs.Points
mypts(mypts.Count).ApplyDataLabels
With mypts(mypts.Count).DataLabel
.ShowSeriesName = True
.ShowCategoryName = False
.ShowValue = False
' optional parameters
.Orientation = 0
.Position = xlLabelPositionAbove
.Font.Size = 10
.Font.Bold = True
End With
Does any body know how to center the data labels, which I gave it by giving each series a name?
Centering a label above each line will involve creating another data series that calculates the line's center. Without having access to your data, I turned to #JonPeltier 's excellent post on connecting two XY data series.
Your question involves your custom VBA code. My example here should be taken as the steps needed to set up the data. At your choice you can either set up your data on the worksheet, or have your VBA code create this "extra" data series to add to the chart (again, because I don't know what your data looks like I can't recommend a solution specific to your problem).
I won't repeat all the details of creating the chart, but here's an example of the data and the resulting chart:
Now, setting up the mid-point data isn't difficult. The mid-point is a quick formula =((D2-A2)/2)+A2, copied down the column.
Added to the chart, select the "MidPoint" and "Value" columns and cntl+c copy the data, then select the chart and "Paste Special" as a new data series.
A Quick Note: DO NOT put your mid-point data on the same rows as the A and B data. I did this initially and Excel (in its own private wisdom) associated the data with column A. The results on the chart aren't pretty.
Next to last step is to select the new data series and select "Add Data Labels", then check the box for "Value From Cells". Choose the data range for the labels, e.g. cells C17:C20.
Finally, format the labels to only show the "Value From Cells" (uncheck the "Y" data label) and set the marker to "None". Then you have the centered label for your line.

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!

Adding Names to Scatter Plot Points Without Modifying X-Values (Excel 2007 VBA)

I am attempting to modify the tooltips of a scatter plot using Visual Basic code so that the name of the data points are in the tooltips when you click on individual data points, along with the x and y data from the plot.
I have already attempted to use:
ThisWorkbook.Worksheets("Scatter Plot").ChartObjects(1).Chart.SetSourceData Source:=ThisWorkbook.Worksheets("Sheet1").Range(col1 & ", " & col2), PlotBy:=xlColumns
ThisWorkbook.Worksheets("Scatter Plot").ChartObjects(1).Chart.SeriesCollection(1).XValues = ThisWorkbook.Worksheets("Sheet1").Range(col3)
But when I try to use it, the macro overwrites the X-value data already stored in the data points in order to add the names to the scatter plot tooltips. Is there any way that I can modify the names of the scatter plot points without modifying their x-values or using Add-Ins?
The following code sets the Data Label (Data Callout) to the values provided in the Range "Sheet1!$K$10:$K$20". Change this reference to the cells where you have the content you would like to display and you should be good to go.
Best regards
Christian
ThisWorkbook.Worksheets("Scatter Plot").ChartObjects(1).Chart.SeriesCollection(1).DataLabels.Format.TextFrame2.TextRange. InsertChartField msoChartFieldRange, "=Sheet1!$K$10:$K$20", 0
Then add the following to also display them properly:
With ThisWorkbook.Worksheets("Scatter Plot").ChartObjects(1).Chart.SeriesCollection(1).
.ShowRange = True
.ShowCategoryName = False
.ShowValue = False
End With

Reinstate Excel chart default resizing behaviour using 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

Attaching a Textbox to a point or line on a chart in Excel/VBA

I was wondering how to attach a textbox to a point or line in an Excel chart for the macro I am working on. I have been using the .AddTextbox method such as
.Shapes.AddTextbox(msoTextOrientationHorizontal, 150, 250, 100, 15) _
.TextFrame.Characters.Text = "Temperature"
But I have to then manually drag the textbox over the line on the chart it is representing as the orientation is of the chart not the line. Is there a way to convert the line/point to a chart orientation which I could use as a variable? or another way? Possibly using the datalabel function, though I want to be able to customize one of the axis locations. Thanks
To solve your question you need to get the left & top position of two objects:
chart itself, which position is set in relation to top-left corner of sheet range area
point in series which position is set in relation to top-left corner of chart
Combination of both result with the following code (fixed parameters-required changes to your situation, could be more dynamic with loop)
Sub Add_Text_to_point()
Dim tmpCHR As ChartObject
Set tmpCHR = Sheet1.ChartObjects(1) 'put index of your chartobject here
'for first serie, for point 2nd here
'(change accordingly to what you need)
With tmpCHR.Chart.SeriesCollection(1).Points(2)
Sheet1.Shapes.AddTextbox(msoTextOrientationHorizontal, _
.Left + tmpCHR.Left, _
.Top + tmpCHR.Top, _
100, 15) _
.TextFrame.Characters.Text = "Temperature"
End With
End Sub
After result presenting the picture below.
Another option would be to use the data labels of Excel. I see two more elegant options:
Make a new data series with just one entry in your chart, give the series the coordinates and the name of the label you want to see. Now activate the marker option for the series (if not done already), right-click on the data point, click "add data labels". Now you'll see the y-Value of the point. By right-clicking again and choosing "Format Data Labels" you can change the text to the series name, also the position, the border, etc. are modifiable. Below an example with two data points. You could delete the second point, the line and the marker but like this you see how it works.
Similarly to the solution from KazJaw you can use the actual data points of your series for attaching custom data labels. This requires some coding, I used this for the chart named "Topview" and wrote percentages next to the data point
Sub Add_Text_to_data_points()
percentages(1) = 0.1
percentages(2) = 0.23
'.... further entries
chartNumber = findChartNumber("Topview")
collNumber = 12 ' index of the "points" series
Set tmpCHR = ActiveSheet.ChartObjects(chartNumber)
For i = 1 To tmpCHR.Chart.SeriesCollection(collNumber).Points.count
With tmpCHR.Chart.SeriesCollection(collNumber).Points(i)
If percentages(i) <> 0 Then
.DataLabel.Text = format(percentages(i), "0%")
End If
End With
Next
End Sub