Create a simple line graph in powerpoint using VBA - vba

I would like to create VBA code that just draws a simple line chart on the first powerpoint sheet.
I wrote the following:
Sub createSampeChart()
Set myDocument = ActivePresentation.Slides(1)
myChart = myDocument.Shapes.AddChart.Chart
With myChart
.ChartStyle = 4
.ApplyLayout 4
.ClearToMatchStyle
.HasLegend = False
End With
End Sub
Running it however gives me a 438 error however. Any thoughts on what I should adjust?

myChart = myDocument.Shapes.AddChart.Chart
Use Set when assigning objects:
Set myChart = myDocument.Shapes.AddChart.Chart
'^^^^
The rest of your code seems correct and should work fine after this correction, provided you have at least one slide in the presentation.

Related

Creating a chart in powerpoint using VBA only without embedded excel data

I am working on a personal powerpoint project and I thought it would be cool to use activex in the powerpoint to make the slides a bit more interactive. I have some activex boxes where you can set a population and an annual growth rate and the final step would be for me to plot the 5 year projection data i am getting on a line graph. I have tried it using excel based VBA but most solutions seem to require pulling data from a sheet so won't work in powerpoint.
I have also tried the following code to build a chart skipping the need for a worksheet but to no avail as I get a runtime error 424: Object required error:
Sub AddChart()
Dim cht As Chart
Dim ser As Series
Set cht = Charts.Add
cht.ChartType = xlColumnClustered
Set ser = cht.SeriesCollection.NewSeries
ser.XValues = Array(1, 3, 5, 7, 9)
ser.Values = Array(2.4, 3.2, 5.7, 12.67)
End Sub
Any solutions in mind or am I flogging a dead horse here?
Thanks!
Powerpoint doesn't have Charts.Add, but Shapes.AddChart2 or .AddChart
Something like this should get you going:
Sub AddChart()
Dim cht As Chart
Dim ser As Series
Set cht = ActivePresentation.Slides(1).Shapes.AddChart(-1, xlColumnClustered).Chart
Set ser = cht.SeriesCollection.NewSeries
ser.XValues = Array(1, 3, 5, 7, 9)
ser.Values = Array(2.4, 3.2, 5.7, 12.67)
End Sub
I know this is an old thread but in case someone stumbles on it like I did - you can paste an empty chart on a Master Layout and then copy it to any slide you need it on, that way Excel never launches to 'create' the chart object, although it is still 'embedded'.
If you create a special layout for it, just be sure to include a Title or some other placeholder because slides with no placeholders get helpfully removed/left behind by PowerPoint during certain operations - such as copying a slide into a new presentation and selecting 'Keep Source Formatting'.

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

VBA Chart automation using ActivateChartDataWindow

I'm building a chart automation script in powerpoint and i have any issue when calling upon "ActivateChartDataWindow".
I would use "Activate" instead of "ActivateChartDataWindow", but "Activate" loads the full Excel program and makes the whole routine run slow and ulgy.
The problem I have is that "ActivateChartDataWindow" does work to populate the charts, but when I manually go to edit the data - right click, edit data - to access the excel application, it does not seem to want to load!
It has been driving my crazy for the last 5 hours and would appreciate any ideas on how to over come this.
OLE.dlll are working correctly and the code I am using is given below.
Code below:
There are 5 slides with one chart on each page and the code below is what i am using as a point of concept
I have a felling i am using "ActivateChartDataWindow" wrong, but there is not much on the web to know what i am doing wrong! Arrrhhhh!
For i = 1 To 5
Set instance = Nothing
Set instance = ActivePresentation.Slides(i).Shapes(1).Chart.ChartData
With instance
.ActivateChartDataWindow
instance.Workbook.Sheets(1).Range("A1:H26").Value = 27
instance.Workbook.Close
End With
Next i
End Sub
As always recommended, you don't need to Activate an object to modify it. If you're trying to handle a Workbook embedded in a slide, you can do it this way
' This function will get you a Workbook object embedded in a Slide (late binding)
Function getEmbeddedWorkbook(sld As Slide) As Object
Dim shp As Shape
On Error Resume Next
For Each shp In sld.Shapes
If shp.Type = 3 Then ' embedded chart workbook created in PP
Set getEmbeddedWorkbook = shp.Chart.ChartData.Workbook
Exit Function
End If
If shp.Type = 7 Then ' embedded workbook pasted from excel
Set getEmbeddedWorkbook = shp.OLEFormat.Object
Exit Function
End If
Next
End Function
' For Testing, I have 6 slides, Some have a workbook pasted from Excel
' OLE, shape type = 7, others have a chart created in PP (type = 3)
Sub Test()
Dim wb As Object, i As Long
For i = 6 To 6 'ActivePresentation.Slides.Count
Set wb = getEmbeddedWorkbook(ActivePresentation.Slides(i))
If Not wb Is Nothing Then
wb.Sheets(1).Range("A1:D5").Value = i * i
End If
Next
End Sub

Macro for Excel to refrech Labels Chart

I work on Excel and I'm not really familiar with macros assigned to charts. Basically I have several charts. I need each of these charts to have labels that corresponds to data in another spreadsheets called "Data_SC". So for instance I would have:
Graph1: Label_1 = Data_SC!A1 ;
Label_2 = Data_SC!A2...
Graph2:
Label_1 = Data_SC!B1 ;
Label_2 = Data_SC!B2...
I tried to do it only for the first labels of each charts but I get the error "Type:mismatch". Here is my code:
Sub Refresh_Labels()
Dim cht As ChartObjects
For Each cht In Sheets("Sheet1").ChartObjects
cht.SeriesCollection(1).Points(1).HasDataLabels = True
cht.SeriesCollection(1).Points(1).DataLabel(1).Text = Sheets("Data_SC").Range(A1)
Next cht
End Sub
Could you guys help me please?
This should work:
Sub Refresh_Labels()
Dim cht As ChartObject
For Each cht In Sheets("Sheet1").ChartObjects
cht.Chart.SeriesCollection(1).Points(1).HasDataLabel = True
cht.Chart.SeriesCollection(1).Points(1).DataLabel.Text = Sheets("Data_SC").Range("A1")
Next cht
End Sub

VBA activate chart created in different function

Say I have created a chart in one function as shown:
Sub CreateChart()
Dim sh As Worksheet
Dim chrt as Chart
Set sh = ActiveWorkbook.Worksheets("Sheet1")
Set chrt = sh.Shapes.AddChart.Chart
End Sub
How can I activate this chart in a different function where I want to move it to a certain cell? I am using the following code but it keeps giving me errors and won't activate the chart. I even gave the chart a Title and tried to use it's title t activate it but it won't recognize the name:
Sub MoveChart()
ActiveSheet.ChartObjects("chrt").Activate
With ActiveChart.Parent
.Left = Range("N2").Left
End With
Why activate it? You may use directly the chrt object that you stored, which you may pass to a parametrized MoveChart subroutine:
Sub MoveChart(ByVal chrt As Excel.Chart)
With chrt.Parent
.Left = Range("N2").Left
End With
End Sub
with the difference that now you may move any chart you'd like.
Later edit
The second macro fails because the chart remains unnamed. Trying to access the chart by the name of the VBA variable doesn't do the trick. So, try this:
Sub CreateChart()
Dim chrt As Shape
With ActiveWorkbook.Worksheets("Sheet1").Shapes
Set chrt = .AddChart()
Let chrt.Name = "New chart"
End With
End Sub
Sub MoveChart()
With ActiveWorkbook.Worksheets("Sheet1")
.ChartObjects("New chart").Left = .Range("N2").Left
End With
End Sub
Don't forget to modify the code to use other chart names, other sheet names etc.