Is there a way to add a callout label to a point in a chart, without using select? - vba

Is there a way to add a callout label to a point in a chart, without using Select?
Recording a macro, I got this:
Sub Macro9()
ActiveSheet.ChartObjects("SPC").Activate
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.FullSeriesCollection(1).Points(4).Select
ActiveChart.SetElement (msoElementDataLabelCallout)
End Sub
But I would rather like to avoid using Select. I tried simply using the SetElement-method on the point, but that failed. Using the HasDataLabel = True-method simply adds a datalabel.
Is there any workarounds to selecting the point and then using SetElement on the chart, or will I have to settle for something resembling the above macro?

Is this what you are trying? In the below code we have avoided .Activate/.Select completely :)
Feel free to play with .AutoShapeType property. You can also format the data label to show the values in whatever format you want.
Sub Sample()
Dim objC As ChartObject, chrt As Chart, dl As DataLabel
Dim p As Point
Set objC = Sheet1.ChartObjects(1)
Set chrt = objC.Chart
Set p = chrt.FullSeriesCollection(1).Points(4)
p.HasDataLabel = True
Set dl = p.DataLabel
With dl
.Position = xlLabelPositionOutsideEnd
.Format.AutoShapeType = msoShapeRectangularCallout
.Format.Line.Visible = msoTrue
End With
End Sub
Screenshot

As I said in a comment: I couldn't find a way to do this directly but thought I'd be able to work around it.
Turns out I was unsuccessful!
But let's cover an edge case which for some uses will have a pretty easy solution; say you don't need datalabels except for the instances where you want callout:
Sub chartTest()
Dim co As ChartObject
Dim ch As Chart
Dim i As Integer
' The point index we want shown
i = 2
Set co = Worksheets(1).ChartObjects(2)
Set ch = co.Chart
co.Activate
ch.SetElement (msoElementDataLabelCallout)
For j = 1 To s.Points.Count
' We can change this to an array check if we want several
' but not all points to have callout
If j <> i Then s.Points(j).HasDataLabel = False
Next j
End Sub
For anyone desperate, the closest I came was to create an overlay using the original chart as a template. It doesn't work accurately for arbitrary charts, however, due to positioning issues with the callout box.
But at this point, you might as well have just added a textbox or something far less involved than copying a chart, deleting half its contents and making the rest of it invisible...
But for the sake of Cthul-- I mean, science:
Sub pTest()
Dim co As ChartObject
Dim ch As Chart
Dim s As Series
Dim p As Point
Set co = Worksheets(1).ChartObjects(1)
Set ch = co.Chart
Set s = ch.SeriesCollection(1)
i = 2
Call copyChartTest(co, ch, i)
End Sub
Sub copyChartTest(ByRef co As ChartObject, ByRef cht As Chart, ByVal i As Integer)
Dim ch As Chart ' The overlay chart
Set ch = co.Duplicate.Chart
' Set callout
ch.SetElement (msoElementDataLabelCallout)
' Invisibil-ate!
With ch
.ChartArea.Fill.Visible = msoFalse
.SeriesCollection(1).Format.Line.Visible = False
.ChartTitle.Delete
.Legend.Delete
For j = 1 To .SeriesCollection(1).Points.Count
.SeriesCollection(1).Points(j).Format.Fill.Visible = msoFalse
If j <> i Then .SeriesCollection(1).Points(j).HasDataLabel = False
Next j
End With
' Align the charts
With ch
.Parent.Top = cht.Parent.Top
.Parent.Left = cht.Parent.Left
End With
End Sub
And the result: DataLabels intact with only 1 point having callout.

Have you tried this free tool http://www.appspro.com/Utilities/ChartLabeler.htm by Rob Bovey?
There is an option "manual label" which seems to be very close to what you want. I am using the version of 1996-97 which has visible VBA code. I have not checked if the latest version has.

try the below code
Sub Macro9()
ActiveSheet.ChartObjects("SPC").Activate
ActiveChart.SeriesCollection(1).Points(4).HasDataLabel = True
ActiveChart.SeriesCollection(1).Points(4).DataLabel.Text = "Point 4 Test"
End Sub

Related

VBA PowerPoint Slides set custom layout to refresh the layout

I have created a script processing many slides and at the end, some slides seem to have glitches in their layout. For example, slide numbers have moved on some slides but not on others. It can be fixed manually by re-assigned the custom layout to the slide.
How can I do this automatically?
I could just loop over all slides, find out it's custom layout and re-assign it. But how? This code seems to loop infinitely:
Dim sld As Slide
Dim layoutName As String
Dim layoutIndex As Integer
Set sld = Application.ActiveWindow.View.Slide
layoutName = sld.CustomLayout.Name
layoutIndex = getLayoutIndexByName(layoutName)
ActivePresentation.Slides(y).CustomLayout = ActivePresentation.Designs(y).SlideMaster.CustomLayouts(layoutIndex)
Function getLayoutIndexByName(xName As String) As Integer
ActivePresentation.Designs(1).SlideMaster.CustomLayouts.Item (1)
With ActivePresentation.Designs(1).SlideMaster.CustomLayouts
For i = 1 To .Count
Debug.Print ("inLoop Name: " + .Item(i).Name)
If .Item(i).Name = xName Then
getLayoutIndexByName = i
Exit Function
End If
Next
End With
End Function
To simply reapply the layout already assigned, you only need this:
ActivePresentation.Slides(y).CustomLayout = ActivePresentation.Slides(y).CustomLayout
Occasionally, that command doesn't work, then this workaround is worth a try:
DoEvents
Application.CommandBars.ExecuteMso ("SlideReset")
DoEvents
To apply a new layout, then you need to use something like this code, which is pretty similar to yours:
ActivePresentation.Slides(y).CustomLayout = ActivePresentation.Designs(1).SlideMaster.CustomLayouts(GetLayoutIndexFromName("Text Page", ActivePresentation.Designs(1)))
My version of GetLayoutIndexFromName:
Function GetLayoutIndexFromName(sLayoutName As String, oDes As Design) As Long
Dim x As Long
For x = 1 To oDes.SlideMaster.CustomLayouts.Count
If oDes.SlideMaster.CustomLayouts(x).Name = sLayoutName Then
GetLayoutIndexFromName = x
Exit Function
End If
Next
End Function

Replace a text box with a placeholder (Title or Body)

I received a PowerPoint file with multiple slides which were supposed to be templates (designs - customlayouts) but instead were regular slides.
Transforming them into SlideMaster and custom layouts and replacing the titles and bodys (textboxes) with actual placeholders by hand was a pain.
So I came with this script to make the process faster.
If anybody has a better approach, it's welcome.
Had to look for a workaround to get the customlayout object.
Several things are missing, for example error handling.
To test it, copy a textbox into a slidemaster layout slide, select it and run the ReplaceWithPHTitle macro
Option Explicit
Public Sub ReplaceWithPHTitle()
ReplaceTexboxWithPlaceholder ppPlaceholderTitle
End Sub
Public Sub ReplaceWithPHBody()
ReplaceTexboxWithPlaceholder ppPlaceholderBody
End Sub
Private Sub ReplaceTexboxWithPlaceholder(ByVal placeholderType As PpPlaceholderType)
Dim targetLayout As CustomLayout
Dim activeShape As Shape
Dim newPlaceHolder As Shape
Set activeShape = ActiveWindow.Selection.ShapeRange(1)
Set targetLayout = activeShape.Parent
Set newPlaceHolder = targetLayout.Shapes.AddPlaceholder(Type:=placeholderType, Left:=activeShape.Left, Top:=activeShape.Top, Width:=activeShape.Width + 15, Height:=activeShape.Height)
With newPlaceHolder.TextFrame
.TextRange.Font.Name = activeShape.TextFrame.TextRange.Font.Name
.TextRange.Characters.Font.Color.RGB = activeShape.TextFrame.TextRange.Characters.Font.Color.RGB
.TextRange.Font.Size = activeShape.TextFrame.TextRange.Font.Size
.TextRange.Font.Bold = activeShape.TextFrame.TextRange.Font.Bold
.TextRange.ParagraphFormat.Bullet.Type = activeShape.TextFrame.TextRange.ParagraphFormat.Bullet.Type
.TextRange.ParagraphFormat.SpaceWithin = activeShape.TextFrame.TextRange.ParagraphFormat.SpaceWithin
.TextRange.ParagraphFormat.Alignment = activeShape.TextFrame.TextRange.ParagraphFormat.Alignment
.TextRange.ParagraphFormat.SpaceBefore = activeShape.TextFrame.TextRange.ParagraphFormat.SpaceBefore
.TextRange.ParagraphFormat.SpaceAfter = activeShape.TextFrame.TextRange.ParagraphFormat.SpaceAfter
.TextRange.ParagraphFormat.BaseLineAlignment = activeShape.TextFrame.TextRange.ParagraphFormat.BaseLineAlignment
.TextRange.Text = activeShape.TextFrame.TextRange.Text
End With
With newPlaceHolder.TextFrame2
.TextRange.Font.Spacing = activeShape.TextFrame2.TextRange.Font.Spacing
End With
newPlaceHolder.ZOrder msoSendToBack
newPlaceHolder.Select
End Sub
Any improvements are welcome too.

Getting a series trend line equation to a shape text box

I'm attempting to get the trend line equation from the first series in my chart to a shape text box placed elsewhere on the worksheet - however, I can only get the textbox to populate correctly when I'm stepping through the code line by line - during run-time it has no effect:
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value
ThisWorkbook.Worksheets("MyDataSheet").Shapes(slopetextboxes(k)).TextFrame.Characters.Text = srs.Trendlines(1).DataLabel.Text
srs.Trendlines(1).DisplayEquation = False 'Turn it back off
Exit For
Next srs
k = k + 1 ' for the slope textboxes
Next chtObj
Note that slopetextboxes is an array containing the names of ~6 shape text boxes.
As far as I know there's no way to get the trend line data label without stopping to display it. I've tried storing it in a string first, DoEvents, and turning Application.ScreenUpdating back on, all to no avail. I'm stumped here.
EDIT: It appears that by placing DoEvents after .DisplayEquation = True I'm able to have some of my shapes populate correctly, but not all. Still appears to be some kind of run-time issue.
BOUNTY EDIT: I've moved ahead to grab the slopes with a formula ran into the data itself, but I still don't understand why I can't grab the chart's .DataLabel.Text during run-time. I can grab it when stepping through, not during run-time. It appears to just take the PREVIOUS series slope and place it in the shape (or a cell, it doesn't even matter where the destination is). DoEvents placed in different spots yields different outcomes, so something must be going on.
Updated with better understanding of the bug. This works for me in excel 2016 with multiple changes to the source data (and therefore the slope)
I tried myChart.refresh - didnt work. I tried deleting and then re-adding the entire trendline, also didnt work.
This works for everything but the first case. First case needs to be hit twice. Same as for .select
If you try and delete trendline even after assigning its text to textbox, this wont work
Option Explicit
Sub main()
Dim ws As Worksheet
Dim txtbox As OLEObject
Dim chartObject As chartObject
Dim myChart As chart
Dim myChartSeriesCol As SeriesCollection
Dim myChartSeries As Series
Dim myChartTrendLines As Trendlines
Dim myTrendLine As Trendline
Set ws = Sheets("MyDataSheet")
Set txtbox = ws.OLEObjects("TextBox1")
For Each chartObject In ws.ChartObjects
Set myChart = chartObject.chart
Set myChartSeriesCol = myChart.SeriesCollection
Set myChartSeries = myChartSeriesCol(1)
Set myChartTrendLines = myChartSeries.Trendlines
With myChartTrendLines
If .Count = 0 Then
.Add
End If
End With
Set myTrendLine = myChartTrendLines.Item(1)
With myTrendLine
.DisplayEquation = True
txtbox.Object.Text = .DataLabel.Text
End With
Next chartObject
End Sub
Here's my code that seems to definitely work when just pressing F5:
Basically, I store the text in a collection, then iterate through all of the textboxes to add the text to the textboxes. If this wasn't precisely what you were asking for, then I hope this helps in any way.
Sub getEqus()
Dim ws As Worksheet
Dim cht As Chart
Dim srs As Variant
Dim k As Long
Dim i As Long
Dim equs As New Collection
Dim shp As Shape
Dim slopetextboxes As New Collection
Set ws = Excel.Application.ThisWorkbook.Worksheets(1)
'part of the problem seemed to be how you were defining your shape objects
slopetextboxes.Add ws.Shapes.Range("TextBox 4")
slopetextboxes.Add ws.Shapes.Range("TextBox 5")
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value
equs.Add srs.Trendlines(1).DataLabel.Text
srs.Trendlines(1).DisplayEquation = False 'Turn it back off
Next srs
Next chtObj
For i = 1 To slopetextboxes.Count
'test output i was trying
ws.Cells(i + 1, 7).Value = equs(i)
slopetextboxes(i).TextFrame.Characters.Text = equs(i)
Next
End Sub
Pictures of what the output looks like when i just press the button
Good luck!
This worked for me - I loop through multiple charts on Sheet1, toggling DisplayEquation and then writing the equation to a textbox/shape on the different worksheet. I used TextFrame2.TextRange but TextFrame worked as well, if you prefer that. I wrote to both a regular text box, as well as a shape, which was probably overkill as the syntax is the same for both.
This gets the trendline equation from the first Series - it sounded like you didn't want to loop through all the Series in the SeriesCollection.
Sub ExtractEquations()
Dim chtObj As ChartObject
Dim slopeTextBoxes() As Variant
Dim slopeShapes() As Variant
Dim i As Integer
slopeTextBoxes = Array("TextBox 1", "TextBox 2", "TextBox 3")
slopeShapes = Array("Rectangle 6", "Rectangle 7", "Rectangle 8")
For Each chtObj In ThisWorkbook.Sheets("Sheet1").ChartObjects
With chtObj.Chart.SeriesCollection(1).Trendlines(1)
.DisplayEquation = True
ThisWorkbook.Sheets("MyDataSheet").Shapes(slopeTextBoxes(i)).TextFrame2.TextRange.Characters.Text = .DataLabel.Text
ThisWorkbook.Sheets("MyDataSheet").Shapes(slopeShapes(i)).TextFrame2.TextRange.Characters.Text = .DataLabel.Text
.DisplayEquation = False
i = i + 1
End With
Next chtObj
End Sub
I've written this off as a bug - The only workaround was discovered by BrakNicku which is to Select the DataLabel before reading its Text property:
srs.Trendlines(1).DataLabel.Select
Not a sufficient solution (since this can cause some issues during run-time), but the only thing that works.
I had a similar issue running the code below and my solution was to run Application.ScreenUpdating = True between setting the trendline and querying the DataLabel. Note that screen updating was already enabled.
'Set trendline to the formal y = Ae^Bx
NewTrendline.Type = xlExponential
'Display the equation on the chart
NewTrendline.DisplayEquation = True
'Add the R^2 value to the chart
NewTrendline.DisplayRSquared = True
'Increse number of decimal places
NewTrendline.DataLabel.NumberFormat = "#,##0.000000000000000"
'Enable screen updating for the change in format to take effect otherwise FittedEquation = ""
Application.ScreenUpdating = True
'Get the text of the displated equation
FittedEquation = NewTrendline.DataLabel.Text
If it works when you step through, but not when it runs then it's an issue with timing and what Excel is doing in between steps. When you step through, it has time to figure things out and update the screen.
FYI, Application.Screenupdating = False doesn't work when stepping
through code. It gets set back to True wherever the code pauses.
When did you give it a chance to actually do the math and calculate the equation? The answer is that, you didn't; hence why you get the previous formula.
If you add a simple Application.Calculate (in the right spot) I think you'll find that it works just fine.
In addition, why should Excel waste time and update text to an object that isn't visible? The answer is, it shouldn't, and doesn't.
In the interest of minimizing the amount of times you want Excel to calculate, I'd suggest creating two loops.
The first one, to go through each chart and display the equations
Then force Excel to calculate the values
Followed by another loop to get the values and hide the equations again.
' Display the labels on all the Charts
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value
' I take issue with the next line
' Why are you creating a loop, just for the first series?
' I hope this is just left over from a real If condition that wan't included for simplicity
Exit For
Next srs
Next chtObj
Application.ScreenUpdating = True
Application.Calculate
Application.ScreenUpdating = False
' Get the Equation and hide the equations on the chart
For Each chtObj In ActiveSheet.ChartObjects
Set cht = chtObj.Chart
For Each srs In chtObj.Chart.SeriesCollection
ThisWorkbook.Worksheets("MyDataSheet").Shapes(slopetextboxes(k)).TextFrame.Characters.Text = srs.Trendlines(1).DataLabel.Text
srs.Trendlines(1).DisplayEquation = False 'Turn it back off
Exit For
Next srs
k = k + 1 ' for the slope textboxes
Next chtObj
Application.ScreenUpdating = True
Update:
I added a sample file based on your description of the issue. You can select 4 different options in an ActiveX ComboBox which copies values to the Y-Values of a chart. It shows the trend-line equation below, based on the formula & through copying the value from the chart into a Textbox shape.
Maybe 2016 is different, but it works perfectly in 2013. Try it out...
Shape Text Box Example.xlsm

Wrong positioning of the shape in MS Word using vba

I'm writing a simple code to position my shapes (which are actually pictures) in the document. I want them to be positioned:
horizontally to exactly 0 mm. from the left side of the printable area
vertically to 7 mm. below the paragraph (to which the shape is anchored)
I wrote a simple code:
Selection.ShapeRange.RelativeHorizontalPosition = wdRelativeHorizontalPositionColumn
Selection.ShapeRange.Left = MillimetersToPoints(0)
Selection.ShapeRange.RelativeVerticalPosition = wdRelativeVerticalPositionParagraph
Selection.ShapeRange.Top = MillimetersToPoints(7)
Selection.ShapeRange.WrapFormat.Type = wdWrapTopBottom
For 1 shape on the page it works fine. But if there are more then 1 shape, it somehow "throws" the 2nd shape to the top of the page. It looks like Word anchors it to the 1st paragraph on the page. but it shouldn't. At the same time horizontal positioning is ok.
I would appreciate any help to fix this issue.
My possible solution for this issue will look as follows:
Sub PositShape_3()
Dim I As Integer
If Selection.InlineShapes.Count <> 0 Then
For I = Selection.InlineShapes.Count To 1 Step -1
Selection.InlineShapes(I).ConvertToShape
Next I
End If
Selection.ShapeRange.RelativeHorizontalPosition = wdRelativeHorizontalPositionColumn
Selection.ShapeRange.Left = MillimetersToPoints(0)
Selection.ShapeRange.RelativeVerticalPosition = wdRelativeVerticalPositionLine
Selection.ShapeRange.Top = MillimetersToPoints(7)
Selection.ShapeRange.WrapFormat.Type = wdWrapTopBottom
End Sub
In spite of the fact that the use of wdRelativeVerticalPositionLine solved the problem, it is still interesting why the use of wdRelativeVerticalPositionParagraph has such unexpected unwanted consequences.
Note the use of SELECTION in the code you show us. If you don't change the paragraph selection, then the shapes will always be anchored to the same paragraph. Working with a Selection in Word is tricky; it's much better to work with a more tangible object, such as a specific paragraph.
The following code sample illustrates using paragraph objects to anchor and position successively added Shapes.
Sub insertShapesProgressively()
Dim shp As word.Shape
Dim shpRng As word.ShapeRange
Dim rng As word.Range
Dim iParaCounter As Long
'We want to insert the Shape anchored to three different paragraphs
' on the same page
For i = 7 To 9
Set rng = ActiveDocument.Paragraphs(i).Range
Set shp = ActiveDocument.shapes.AddShape(msoShapeWave, 0, 0, 10, 10, rng)
Set shpRng = rng.ShapeRange
shpRng.RelativeHorizontalPosition = wdRelativeHorizontalPositionColumn
shpRng.Left = MillimetersToPoints(0)
shpRng.RelativeVerticalPosition = wdRelativeVerticalPositionParagraph
shpRng.Top = MillimetersToPoints(7)
shpRng.WrapFormat.Type = wdWrapTopBottom
Next
End Sub

Excel 2007 VBA Problem setting Axis Title

I need help setting the X and Y axes title inside Excel 2007 VBA. It keeps complaining about "Object required":
Sub macro2()
Dim xAxis As Axis
icount = 1
Charts.Add
Charts(icount).Name = iskewplane & "deg Skew Plane"
Charts(icount).Activate
Set xAxis = Charts(icount).Axes(xlCategory)
With xAxis
.Axis
.AxisTitle.Text = "Theta (deg)"
End With
Is there something wrong in my code? I tried recording the macro during setting the axis title name, but the macro is blank during the name setting.
Any help is appreciated
You should use Option Explicit because iCount wasn't defined and iskewplane wasn't either.
Here is the right code:
Sub mac()
Dim xAxis As Axis
Dim iCount As Integer
iCount = 1
Charts.Add
Charts(iCount).Name = "deg Skew Plane"
Charts(iCount).Activate
Set xAxis = Charts(iCount).Axes(xlCategory)
With xAxis
.HasTitle = True
.AxisTitle.Caption = "Theta (deg)"
End With
End Sub
You first have to create the AxisTitle object - an axis doesn't automatically have one. This is done by setting Axis.HasTitle = True - a slightly unusual method.