I have been working on automating the copying of editable charts from an excel workbook to a PowerPoint presentation through VBA. I got a lot of help through this link Using VBA to Paste Excel Chart with Data into PowerPoint which has sorted the copy-pasting bit.
Sub CopyChartSlide2()
Application.ScreenUpdating = False
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht1 As Excel.ChartObject
Dim Data As Excel.Worksheet
Dim pptcht1 As PowerPoint.Shape
Dim iLoopLimit As Long
Dim OpenPptDialogBox As Object
Dim SlideIndex As Long
Application.ScreenUpdating = False
'Look for existing instance
Set newPowerPoint = CreateObject("PowerPoint.Application")
Set OpenPptDialogBox = newPowerPoint.FileDialog(msoFileDialogOpen)
If OpenPptDialogBox.Show = -1 Then
newPowerPoint.Presentations.Open (OpenPptDialogBox.SelectedItems(1))
End If
Set activeSlide = newPowerPoint.ActivePresentation.Slides(1)
SlideIndex = 1
Set Data = Worksheets("Slide2")
Set cht1 = Data.ChartObjects("Chart1")
cht1.Copy
newPowerPoint.CommandBars.ExecuteMso "PasteExcelChartDestinationTheme"
DoEvents
On Error Resume Next
Do
DoEvents
Set pptcht1 = activeSlide.Shapes(activeSlide.Shapes.Count)
If Not pptcht1 Is Nothing Then Exit Do
iLoopLimit = iLoopLimit + 1
If iLoopLimit > 100 Then Exit Do
Loop
On Error GoTo 0
Debug.Print "iLoopLimit = " & iLoopLimit
With pptcht1
.Left = 103.68
.Top = 84.24
End With
iLoopLimit = 0
AppActivate newPowerPoint.Caption
Set activeSlide = Nothing
Set newPowerPoint = Nothing
Application.ScreenUpdating = True
End Sub
However, when the charts get pasted, it embeds the entire workbook instead of just the worksheet. Since I am working with a workbook of around 20 sheets, and each time a chart is pasted into the presentation, the entire workbook gets embedded and since there are many charts, it makes the PPT heavy and makes the process very slow. Is there a way to only embed the worksheet that is relevant to the chart?
Related
I am trying to paste an excel chart in a powerpoint slide, however, losing the source formatting in the process. Request you to please help me with the code.
Currently I am using the following code:
Sub EuropeMoneyBall()
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
Dim MainWB As Workbook
Dim MBSheet1 As Worksheet
Dim MBSheet2 As Worksheet
Application.DisplayAlerts = False
'*****************Open Excel file where charts are saved*********************
Workbooks.Open Filename:="J:\Research\Internal\Moneyball.xlsx"
Set MainWB = Workbooks("Moneyball.xlsx")
Set MBSheet1 = MainWB.Sheets("1Y Charts")
Set MBSheet2 = MainWB.Sheets("3Y Charts")
'*****************Open Powerpoint where charts are to be saved********************
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
Set myPresentation = PowerPointApp.ActivePresentation
Set mySlide = myPresentation.Slides(16)
MBSheet1.Activate
MBSheet1.ChartObjects("Chart 1").Chart.ChartArea.Copy
With mySlide
With .Shapes.Paste
.Top = Application.CentimetersToPoints(4.11)
.Left = Application.CentimetersToPoints(0.73)
.Height = Application.CentimetersToPoints(9.47)
.Width = Application.CentimetersToPoints(11.54)
End With
End With
myPresentation.Application.CommandBars.ExecuteMso "PasteExcelChartSourceFormatting"
MBSheet2.Activate
MBSheet2.ChartObjects("Chart 1").Chart.ChartArea.Copy
With mySlide
With .Shapes.Paste
.Top = Application.CentimetersToPoints(4.11)
.Left = Application.CentimetersToPoints(12.87)
.Height = Application.CentimetersToPoints(9.47)
.Width = Application.CentimetersToPoints(11.54)
End With
End With
Application.DisplayAlerts = True
End Sub
Any help is appreciated.
Thanks
Rohan
I am trying to copy a specific range from excel and past it in pp as a picture. I have pieced together the following code from various online sources and continue to get a run time 91 error ( Object Variable or With block variable not set) when running PowerPointApp.WindowState = 2.
How can I fix this error, and avoid it in future?
first i successfully run
Private Sub OpenPowerpoint()
Dim PPT As PowerPoint.Application
Set PPT = New PowerPoint.Application
PPT.Visible = True
PPT.Presentations.Open Filename:="C:\Users\aofarrell\Desktop\CYB\Weekly Pack Update - Template.pptx"
PPT.ActivePresentation.Slides(2).Select
End Sub
Then I attempt to run
Private Sub CopyToPowerPoint()
Dim rng As Range
Dim PowerPointApp As Object
Dim mySlide As Object
Dim myShape As Object
'Copy Range from Excel
Set rng = ThisWorkbook.Sheets("Triggers").Range("B6:Z33")
'Copy Excel Range
rng.Copy
'Paste to PowerPoint and position
PowerPointApp.WindowState = 2 'ERROR OCCURS HERE
mySlide.Shapes.PasteSpecial DataType:=0
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'Set position:
myShape.Left = 20
myShape.Top = 70
myShape.Width = 675
myShape.Height = 400
'Clear The Clipboard
Application.CutCopyMode = False
Application.Wait (Now + TimeValue("00:00:01"))
End Sub
Hmm... Well, first you need to define what type of Object your PowerPointApp is. And what specific object your mySlide is. Remember also that Local variables are destroyed at the end of the Sub/Function, so you may want some Module level variables/objects instead:
Option Explicit
Private PPT As PowerPoint.Application
Private PPT_pres As PowerPoint.Presentation
Private Sub OpenPowerpoint()
Set PPT = New PowerPoint.Application
PPT.Visible = True
Set PPT_pres = PPT.Presentations.Open(FileName:="C:\Users\aofarrell\Desktop\CYB\Weekly Pack Update - Template.pptx")
PPT_pres.Slides(2).Select
End Sub
Private Sub CopyToPowerPoint()
If PPT Is Nothing Then Exit Sub
If PPT_pres Is Nothing Then Exit Sub
Dim rng As Range
Dim mySlide As Object
Dim myShape As Object
Set mySlide = PPT_pres.Slides(2)
'Copy Range from Excel
Set rng = ThisWorkbook.Sheets("Triggers").Range("B6:Z33")
'Copy Excel Range
rng.Copy
'Paste to PowerPoint and position
PPT.WindowState = 2
mySlide.Shapes.PasteSpecial DataType:=0
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'Set position:
myShape.Left = 20
myShape.Top = 70
myShape.Width = 675
myShape.Height = 400
'Clear The Clipboard
Application.CutCopyMode = False
Application.Wait (Now + TimeValue("00:00:01"))
End Sub
(Also: if I was copying as an Image from Excel to PowerPoint, I would usually use Range.CopyPicture xlPrinter rather than Shapes.PasteSpecial which changes the size of the image based on your screen resolution)
I have developed vba code in excel to show all charts in excel to different slides in ppt. But i want the vba code to be implemented in powerpoint instead of excel so that i can create an addin in powerpoint with that macro. I have tried to implement the excel vba code in powerpoint but that doesnot work in ppt. The problem is that it is copying the charts from the excel to the ppt slides.`I have used the following code in ppt but with no success.
Sub Button1()
Set pptApp = New PowerPoint.Application
Set pptPres = pptApp.ActivePresentation
Dim xlApp As Object
Dim xlWorkBook As Object
Dim wb As Workbook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open("C:\Users\tonmoy.roy\Desktop\Meeting Files\Monthly Review July 10.xls", True, False)
Dim WAIT As Double
WAIT = Timer
While Timer < WAIT + 10
DoEvents 'do nothing
Wend
wb.Activate
Dim ws As Worksheet
Dim intChNum As Integer
Dim objCh As Object
'Count the embedded charts.
For Each ws In wb.Worksheets
intChNum = intChNum + ws.ChartObjects.Count
Next ws
'Check if there are chart (embedded or not) in the active workbook.
If intChNum + ActiveWorkbook.Charts.Count < 1 Then
MsgBox "Sorry, there are no charts to export!", vbCritical, "Ops"
Exit Sub
End If
'Loop through all the embedded charts in all worksheets.
For Each ws In wb.Worksheets
For Each objCh In ws.ChartObjects
Call pptFormat(objCh.Chart)
Next objCh
Next ws
'Loop through all the chart sheets.
For Each objCh In wb.Charts
Call pptFormat(objCh)
Next objCh
'Show the power point.
pptApp.Visible = True
'Cleanup the objects.
Set pptSlide = Nothing
Set pptPres = Nothing
Set pptApp = Nothing
'Infrom the user that the macro finished.
MsgBox "The charts were copied successfully to the new presentation!", vbInformation, "Done"
End Sub
Private Sub pptFormat(xlCh As Chart)
'Formats the charts/pictures and the chart titles/textboxes.
Dim chTitle As String
Dim j As Integer
On Error Resume Next
'Get the chart title and copy the chart area.
chTitle = xlCh.ChartTitle.Text
xlCh.ChartArea.Copy
'Count the slides and add a new one after the last slide.
pptSlideCount = pptPres.Slides.Count
Set pptSlide = pptPres.Slides.Add(pptSlideCount + 1, ppLayoutBlank)
'Paste the chart and create a new textbox.
pptSlide.Shapes.PasteSpecial ppPasteJPG
If chTitle <> "" Then
pptSlide.Shapes.AddTextbox msoTextOrientationHorizontal, 12.5, 20, 694.75, 55.25
End If
'Format the picture and the textbox.
For j = 0 To pptSlide.Shapes.Count
With pptSlide.Shapes(j)
'Picture position.
If .Type = msoPicture Then
.Top = 87.84976
.Left = 33.98417
.Height = 422.7964
.Width = 646.5262
End If
'Text box position and formamt.
If .Type = msoTextBox Then
With .TextFrame.TextRange
.ParagraphFormat.Alignment = ppAlignCenter
.Text = chTitle
.Font.Name = "Tahoma (Headings)"
.Font.Size = 28
.Font.Bold = msoTrue
End With
End If
End With
Next j
End Sub
Private Sub pptFormat(xlCh As Chart) should be :
Private Sub pptFormat(xlCh As Excel.Chart).
PowerPoint has a Chart in its Object Model, so you need to change it to explicitly say Excel.Chart
I am assuming you already have the references
If intChNum + ActiveWorkbook.Charts.Count < 1 Then should be:
If intChNum + wb.Charts.Count < 1 Then
Also your variables aren't declared properly as far as I can see in the pptFormat function. Dim them and use Option Explicit in your coding.
Option Explicit helps in long run more than any inconvenience of having to type out decs.
Tonmoy Roy,
You should ask your second question in another thread. But here is some code to have you select a file and get it's name, path or just the entire name/path
Set XLapp = New Excel.Application
'choose the data file
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Select the Data File (Data File.xlsx)."
'clear filters so all file are shown
.Filters.Clear
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
FullName = .SelectedItems(1) 'name and path
End If
End With
fname = Dir(FullName) ' gets just the file name and not the path
XLapp.Visible = True
Set xlWorkBook = XLapp.Workbooks.Open(FullName, False, True) 'Opens the data xlsx file
I have built a workbook to facilitate the creation of a monthly report presentation I am in charge of. The workbook has some data sheets, some processing sheets and then numbered sheets which contain the charts I need to paste to the corresponding slide. So far, I've built the VBA for opening the PowerPoint template and looping through each excel sheet, and discriminating which sheet names are numeric, and then activating the corresponding slide on the powerpoint template.
Unlike other solutions to similar problems I've found, I'd like to copy all charts from each numbered sheet to each slide at a time, as they are different in shape, quantities and disposition for each sheet/slide. I've mostly only found people copying one chart at a time and pastying as image, which will also not work for me (I need to fine tune data labels and position on the final slide). Any hints as to how could I achieve that?
Here's what my code looks like so far:
Sub CriarSlides()
Dim pptApp As Powerpoint.Application
Dim pptPres As Powerpoint.Presentation
Dim strFileToOpen As Variant
Dim strFileName As String, Hosp As String
Dim datawb As Workbook
Dim xlsCounter As Integer, xlsSlide As Integer
Set datawb = ThisWorkbook
strFileToOpen = Application.GetOpenFilename _
FileFilter:="Powerpoint Files *.pptx (*.pptx),")
If strFileToOpen = False Then
Exit Sub
Else
Set pptApp = New Powerpoint.Application
pptApp.Visible = True
pptApp.Presentations.Open Filename:=strFileToOpen, ReadOnly:=msoFalse, Untitled:=msoTrue
Set pptPres = pptApp.Presentations(1)
End If
For xlsCounter = datawb.Worksheets.Count To 1 Step -1
If IsNumeric(datawb.Worksheets(xlsCounter).Name) Then
xlsSlide = datawb.Worksheets(xlsCounter).Name
' This is the problematic part
Debug.Print xlsSlide
End If
Next xlsCounter
End Sub
With the following modified code you can paste the chart-objects of each sheet in the corresponding slide:
Sub CriarSlides()
Dim pptApp As PowerPoint.Application, pptPres As PowerPoint.Presentation
Dim strFileToOpen As Variant, sh As Worksheet, ch As ChartObject
strFileToOpen = Application.GetOpenFilename(FileFilter:="Powerpoint Files *.pptx (*.pptx),")
If strFileToOpen = False Then Exit Sub
Set pptApp = New PowerPoint.Application
pptApp.Visible = True
Set pptPres = pptApp.Presentations.Open(fileName:=strFileToOpen, ReadOnly:=msoFalse)
For Each sh In ThisWorkbook.Sheets
If IsNumeric(sh.name) Then
For Each ch In sh.ChartObjects
ch.Copy
With pptPres.Slides(CLng(sh.name)).Shapes.Paste
.Top = ch.Top
.Left = ch.Left
.Width = ch.Width
.Height = ch.Height
End With
Next
End If
Next
End Sub
Answer: TL;DR: pasting a chart with embedded data takes a long time so you have to install a delay to prevent vba from moving on before the paste operation completes.
Question:I'm trying to paste an excel chart with embedded data into a powerpoint presentation. The only thing I am getting hung up on is referring to and positioning the chart in ppt once it has been pasted.
Dim newPowerPoint As PowerPoint.Application
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.ChartArea.Copy
newPowerPoint.CommandBars.ExecuteMso ("PasteExcelChartDestinationTheme")
Since I need to paste multiple charts into single slides, repositioning them is necessary. I try to do that with this piece of code:
newPowerPoint.ActiveWindow.Selection.ShapeRange.Left = 0
but am always met with the error: "Method 'ShapeRange' of object 'Selection' failed".
What's particularly odd is that running the code from start to finish results in this error, but stepping through the code using the F8 key does not.
I have tried every way I can think of to move this chart around but I am totally stuck. Does anyone know how I can do this? Also, please keep in mind that is necessary that the chart have data in it (I can't paste the chart as a picture and I would strongly prefer that the data not be linked).
Thanks,
Steve
edit new modified code with multiple chart objects. I needed to add an if conditional:
If activeSlide.Shapes.Count = 1 Then
GoTo NextiLoop
End If
for additional chart objects because the delay pasting chart 2 makes the loop name chart 1 "pptcht2" since chart2 did not exist yet.
Sub CreatePPT()
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht1 As Excel.ChartObject
Dim Data As Excel.Worksheet
Dim pptcht1 As PowerPoint.Shape
Dim iLoopLimit As Long
Application.ScreenUpdating = False
'Look for existing instance
On Error Resume Next
Set newPowerPoint = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If newPowerPoint Is Nothing Then
Set newPowerPoint = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
If newPowerPoint.Presentations.Count = 0 Then
newPowerPoint.Presentations.Add
End If
'Show the PowerPoint
newPowerPoint.Visible = True
Application.ScreenUpdating = False
'Add a new slide where we will paste the chart
newPowerPoint.ActivePresentation.Slides.Add _
newPowerPoint.ActivePresentation.Slides.Count + 1, ppLayoutText
newPowerPoint.ActiveWindow.View.GotoSlide _
newPowerPoint.ActivePresentation.Slides.Count
Set activeSlide = newPowerPoint.ActivePresentation.Slides _
(newPowerPoint.ActivePresentation.Slides.Count)
activeSlide.Shapes(1).Delete
activeSlide.Shapes(1).Delete
'ActiveSheet.ChartObjects("Chart 1").Activate
Set Data = ActiveSheet
Set cht1 = Data.ChartObjects("Share0110")
Set cht2 = Data.ChartObjects("SOW0110")
Set cht3 = Data.ChartObjects("PROP0110")
cht1.Copy
newPowerPoint.CommandBars.ExecuteMso "PasteExcelChartDestinationTheme"
DoEvents
On Error Resume Next
Do
DoEvents
Set pptcht1 = activeSlide.Shapes(activeSlide.Shapes.Count)
If Not pptcht1 Is Nothing Then Exit Do
iLoopLimit = iLoopLimit + 1
If iLoopLimit > 100 Then Exit Do
Loop
On Error GoTo 0
Debug.Print "iLoopLimit = " & iLoopLimit
With pptcht1
.Left = 25
.Top = 150
End With
iLoopLimit = 0
'ActiveSheet.ChartObjects("Chart 2").Activate
'Set Data = ActiveSheet
cht2.Copy
newPowerPoint.CommandBars.ExecuteMso "PasteExcelChartDestinationTheme"
DoEvents
On Error Resume Next
Do
DoEvents
If activeSlide.Shapes.Count = 1 Then
GoTo NextiLoop
End If
Set pptcht2 = activeSlide.Shapes(activeSlide.Shapes.Count)
If Not pptcht2 Is Nothing Then Exit Do
NextiLoop:
iLoopLimit = iLoopLimit + 1
If iLoopLimit > 100 Then Exit Do
Loop
On Error GoTo 0
Debug.Print "iLoopLimit = " & iLoopLimit
With pptcht2
.Left = 275
.Top = 150
End With
iLoopLimit = 0
AppActivate ("Microsoft PowerPoint")
Set activeSlide = Nothing
Set newPowerPoint = Nothing
End Sub
edit: OLD not working code:
Sub CreatePPT()
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht As Excel.ChartObject
Application.ScreenUpdating = False
'Look for existing instance
On Error Resume Next
Set newPowerPoint = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If newPowerPoint Is Nothing Then
Set newPowerPoint = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
If newPowerPoint.Presentations.Count = 0 Then
newPowerPoint.Presentations.Add
End If
'Show the PowerPoint
newPowerPoint.Visible = True
Application.ScreenUpdating = False
'Add a new slide where we will paste the chart
newPowerPoint.ActivePresentation.Slides.Add newPowerPoint.ActivePresentation.Slides.Count + 1, ppLayoutText
newPowerPoint.ActiveWindow.View.GotoSlide newPowerPoint.ActivePresentation.Slides.Count
Set activeSlide = newPowerPoint.ActivePresentation.Slides(newPowerPoint.ActivePresentation.Slides.Count)
activeSlide.Shapes(1).Delete
activeSlide.Shapes(1).Delete
'ActiveSheet.ChartObjects("Chart 1").Activate
Set Data = ActiveSheet
Set cht1 = Data.ChartObjects("Chart 1")
cht1.Copy
newPowerPoint.CommandBars.ExecuteMso ("PasteExcelChartDestinationTheme")
Set pptcht1 = newPowerPoint.ActiveWindow.Selection
With pptcht1
.Left = 0
End With
AppActivate ("Microsoft PowerPoint")
Set activeSlide = Nothing
Set newPowerPoint = Nothing
End Sub
Do yourself a favor and enter this as the first line of the code module:
Option Explicit
This will force you to declare all variables. You have a lot of undeclared variables, including a couple that are almost the same as the few you did declare. Then go to VBA's Tools menu > Options, and check the Require Variable Declaration on the first tab of the dialog, which will put Option Explicit at the top of every new module.
Declare the shape as a PowerPoint.Shape, then find it using this, since any newly added shape is the last one on the slide:
Set pptcht1 = activeSlide.Shapes(activeSlide.Shapes.Count)
The following line first of all does not need the parentheses, despite the poorly written Microsoft Help article. Second, it takes a long time to run. Excel is already trying to move the shape long before the shape has been created. DoEvents is supposed to help with this by making Excel wait until everything else happening on the computer is finished, but the line is still too slow.
newPowerPoint.CommandBars.ExecuteMso ("PasteExcelChartDestinationTheme")
So I cobbled together a little loop that tries to set the variable to the shape, and keeps looping until the shape is finished being created.
On Error Resume Next
Do
DoEvents
Set pptcht1 = activeSlide.Shapes(activeSlide.Shapes.Count)
If Not pptcht1 Is Nothing Then Exit Do
iLoopLimit = iLoopLimit + 1
If iLoopLimit > 100 Then Exit Do
Loop
On Error GoTo 0
In a small number of tests, I found that the loop would have to run 20 to 60 times. I also crashed PowerPoint a few times. Weird.
I'm sure there are better ways to paste the copied chart and keep the slide's color theme, but off the top of my head I don't know one.
This is unreliable, since the application caption changes with different versions of Office (and again the parentheses are not needed):
AppActivate ("Microsoft PowerPoint")
Use this instead:
AppActivate newPowerPoint.Caption
So your whole code becomes:
` Sub CreatePPT()
Dim newPowerPoint As PowerPoint.Application
Dim activeSlide As PowerPoint.Slide
Dim cht1 As Excel.ChartObject
Dim Data As Excel.Worksheet
Dim pptcht1 As PowerPoint.Shape
Dim iLoopLimit As Long
Application.ScreenUpdating = False
'Look for existing instance
On Error Resume Next
Set newPowerPoint = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If newPowerPoint Is Nothing Then
Set newPowerPoint = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
If newPowerPoint.Presentations.Count = 0 Then
newPowerPoint.Presentations.Add
End If
'Show the PowerPoint
newPowerPoint.Visible = True
Application.ScreenUpdating = False
'Add a new slide where we will paste the chart
newPowerPoint.ActivePresentation.Slides.Add _
newPowerPoint.ActivePresentation.Slides.Count + 1, ppLayoutText
newPowerPoint.ActiveWindow.View.GotoSlide _
newPowerPoint.ActivePresentation.Slides.Count
Set activeSlide = newPowerPoint.ActivePresentation.Slides _
(newPowerPoint.ActivePresentation.Slides.Count)
activeSlide.Shapes(1).Delete
activeSlide.Shapes(1).Delete
'ActiveSheet.ChartObjects("Chart 1").Activate
Set Data = ActiveSheet
Set cht1 = Data.ChartObjects("Chart 1")
cht1.Copy
newPowerPoint.CommandBars.ExecuteMso "PasteExcelChartDestinationTheme"
DoEvents
On Error Resume Next
Do
DoEvents
Set pptcht1 = activeSlide.Shapes(activeSlide.Shapes.Count)
If Not pptcht1 Is Nothing Then Exit Do
iLoopLimit = iLoopLimit + 1
If iLoopLimit > 100 Then Exit Do
Loop
On Error GoTo 0
Debug.Print "iLoopLimit = " & iLoopLimit
With pptcht1
.Left = 0
End With
AppActivate newPowerPoint.Caption
Set activeSlide = Nothing
Set newPowerPoint = Nothing
End Sub`