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

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

Related

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.

Get index of next Row under Chart

I would like to know if there is a better way to get the index of the next row under a chart that is placed in a worksheet. I am placing multiple charts with the .parent.Left /.Top properties, not in a range.
I have multiple choices how do implement that, but I find none of these attrative :
Go trough every row in the worksheet, check if the .Top position of the row is below the chart .Top + .Heigth
get the default height of a cell, divise the .Height of the Chart with it, and i get the approximate number of rows that the chart is filling.
thanks.
You can use the BottomRightCell property of the Shape. For instance:
ActiveSheet.Shapes("ChartName").BottomRightCell.Row
... And then simply add 1 to that result.
EDIT: The Chart's parent is a ChartObject, which has the same property.

Match labels to arrows in Excel flowchart using VBA

I'm writing a code generation tool using VBA in Excel (don't ask why—long story). I need to be able to "parse" a flowchart.
The problem is that Excel allows shapes to contain text, with the exception of connectors: lines and arrows can't contain text. To label an arrow, you just put a text box on top of it—but the box isn't "attached" to the arrow in a way that VBA can easily capture.
For example, a user might draw something like this:
Within my VBA code, I can use ActiveSheet.Shapes to find that the flowchart contains seven shapes: there are five boxes (the two labels are just boxes with no border) and two arrows. Then Shape.TextFrame2 will tell me what's written inside each box, and Shape.ConnectorFormat will tell me which box goes at the start and end of each arrow.
What I need is code that can deduce:
Label A belongs to the arrow from Box 1 to Box 2
Label B belongs to the arrow from Box 1 to Box 3
I can think of three ways of doing this, none of them satisfactory.
Ask the user to group each label with its corresponding arrow.
Find out the coordinates of the endpoints of each arrow, then
calculate which arrows pass through which labels.
Find out the coordinates of the corners of each box, then calculate
which labels lie between which pairs of boxes.
Method 1 makes things easier for the programmer but harder for the user. It opens up a lot of potential for user error. I don't see this as an acceptable solution.
Method 2 would be reasonably easy to implement, except that I don't know how to find out the coordinates!
Method 3 is doable (Shape.Left etc will give the coordinates) but computationally quite messy. It also has potential for ambiguity (depending on placement, the same label may be associated with more than one arrow).
Note that methods 2 and 3 both involve trying to match every label with every arrow: the complexity is quadratic. Typical applications will have 10–50 arrows, so this approach is feasible, if somewhat inelegant.
Does anyone have a better idea? Ideally it would be something that doesn't involve coordinate geometry and complicated logic, and doesn't involve asking users to change the way they draw flowcharts.
Edited to add: example 2 in response to Tim Williams
Here's a label whose bounding box intersects the bounding box of both arrows, and whose midpoint isn't inside the bounding box of either arrow. Visually it's easy for a human to see that it belongs with the left arrow, but programmatically it's hard to deal with. If I can find out the coordinates of the arrows' endpoints, then I can calculate that one arrow passes through the label's box but the other doesn't. But if all I have is the bounding rectangles of the arrows, then it doesn't work.
Interesting problem. What if you considered the range covered by the arrow and the range covered by the textbox and matched them up based on the most overlap.
Sub ListShapes()
Dim shp As Shape
Dim shpArrow As Shape
Dim vaArrows As Variant
Dim i As Long
Dim rIntersect As Range
Dim aBestFit() As String
Dim lMax As Long
vaArrows = Split("Straight Arrow Connector 7,Straight Arrow Connector 9", ",")
ReDim aBestFit(LBound(vaArrows) To UBound(vaArrows))
For i = LBound(vaArrows) To UBound(vaArrows)
Set shpArrow = Sheet1.Shapes(vaArrows(i))
lMax = 0
For Each shp In Sheet1.Shapes
If shp.Name Like "Label*" Then
Set rIntersect = Intersect(Sheet1.Range(shp.TopLeftCell, shp.BottomRightCell), _
Sheet1.Range(shpArrow.TopLeftCell, shpArrow.BottomRightCell))
If Not rIntersect Is Nothing Then
If rIntersect.Count > lMax Then
lMax = rIntersect.Count
aBestFit(i) = shp.Name
End If
End If
End If
Next shp
Next i
For i = LBound(vaArrows) To UBound(vaArrows)
Debug.Print vaArrows(i), aBestFit(i)
Next i
End Sub
I tested this with the five box-two arrow setup and nothing more complicated. I put my two arrows in an array, but I assume you have ways to identify the arrows. I also named my untethered boxes "Label x" so I could identify them, but again I assume you have something more sophisticated.
The code loops through every arrow. Inside that loop, it loops through every shape. If it's a label, then it counts the cells in the intersection of the two ranges. Whichever has the most is stored in the best fit array.
It would be nice if you had a reasonable corpus of flow charts to test this to see where the pitfalls are. I don't think this is necessarily better than use the coordinates, just a different approach.
You can find the coordinates of the arrow's endpoints as follows.
First of all, the .Left, .Top, .Width and .Height properties describe the bounding rectangle of the arrow, as Tim Williams points out.
Next, check the .HorizontalFlip and .VerticalFlip properties. If both are false, then the arrow runs from top left to bottom right in its bounding rectangle. That is, the beginning of the arrow has coordinates (.Left,.Top) and the end has coordinates (.Left+.Width,.Top+.Height).
If either *.Flip is true, then the coordinates need to be swapped around as appropriate. E.g., if .HorizontalFlip is true but .VerticalFlip false, then the arrow runs from (.Left+.Width,.Top) to (.Left,.Top+.Height).
As far as I can tell, this is not documented anywhere on MSDN. Thanks to Andy Pope for mentioning it at excelforums.com.
Given this, method 2 seems like the best approach.

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

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.