Attaching a Textbox to a point or line on a chart in Excel/VBA - 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

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!

How to make a chart/shape free-floating vertically, but not horizontally

Is there a way to use the xlfreefloating function but only to position a graph in one direction but not the other? I have a macro that positions my graph between a certain range of cells. I want it to stay freefloating for the y direction but not the x-direction. So if the graph is to the right of some data cells, and I adjust the cells and make them longer in the x direction, I want the graph to follow. But if I adjust them in the y direction, I want them to stay the same. Thanks!
I found out how to do this myself:
One way to do this is to manually activate the chart AFTER the cells are manipulate, and then position it in terms of left or right wherever you want it. The following code was used after my charts were created, positioned, and cells were manipulated:
Sub MoveCharts()
ActiveSheet.ChartObjects("Chart 7").Activate
With ActiveChart.Parent
.Left = Range("N2").Left
End With
End Sub

Draw in a chart (not a chart object but a Chart) with vba

I'll try to be very precise with my problem but if you have any questions, please ask!
So basicelly I have a column A full of dates (from line 1 to line 80) and a column B full of values (stock prices, and also with the same range).
I have created a chart with this code :
Sub Chart()
Range(Cells(1, 1), Cells(80, 1))Select
Range(Selection, Selection.Offset(0, 1)).Select
Set rSource=selection
ActiveChart.SetSourceData Source:=rSource, PlotBy:=xlColumns
ActiveChart.Location Where:=xlLocationAsNewSheet
end sub
So this is not a chart object but a new chart on a new sheet (I say that because all the things I've read on this subject is dealing with chart objects and not with chart alone in a sheet).
Now what I need is to draw an horizontal line between two dates (a support line).
For example, I need to draw a line between 01/01/2013 (line 1) and 06/25/2013 (line 80).
The line has to stay at the same level on the y-axis (that's what we call an horizontal line :) ) at the level of the stock price of 01/01/2013.
I've tried that :
Sub supportline()
Dim CoordA As Variant
CoordA = [a1:b80]
ActiveChart.Shapes.AddLine(CoordA(1, 1), CoordA(1, 2), CoordA(80, 1), CoordA(80, 2)).Select
end sub
But the line isn't drawn where I want. I think there's a problem of scale but I can't figure out how to have the accurate coordinates.
Thank you very much for your time and your help
EDIT (06/11/2013)
I've simplified the data base to illustrate my problem : http://cjoint.com/?CFksHluf0VD I'm trying to make a line between the two dates (01/01/2013 and 16/01/2013)
If you download this file, you'll see in the VBA part : 1/ Test1 : I've tried to make a line to link 2 points of the chart : if you launch the sub you'll see that the line is drawn but at the wrong scale and wrong place 2/ Test 2: I've tried to make an horizontal line between two points but that doesn't work at all
Test 2 is what I need to do for my original project (an horizontal line which goes from one date to another with the same y-value)
ActiveChart.SeriesCollection(1).Select
With Selection.Format.Line
.Visible = msoTrue
//add line style etc
End with
Then use your select statement to choose which points you want joined.
If you look at this link, I'll think you'll find it most useful
VBA-Controlled Conditional Formatting of Line Chart Lines
http://peltiertech.com/WordPress/conditional-formatting-of-lines-in-an-excel-line-chart-using-vba/
Another question on Stack Overflow
Excel VBA - How do you set line style for chart series?
In response to your comments, please see the answer to this question. It offers some good explanation of using charts (in this case vb.net)
Chart: Show more value descriptions on X-Axis
And a link to MSDN re this
http://msdn.microsoft.com/en-us/library/system.windows.forms.datavisualization.charting.chart.aspx

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.