I was using the below code just fine on all the version of excel
- Basically I created a excel sheet with ppt look and export the sheet range to PPT.
Excel VBA to Export to PPT works fine in all versions till office 365 32bit
Its not working in 365 64 bit, Windows 10 OS
Tried the following
Checked reference - with 14,15,16 object library - works fine..
Not working on 64bit - Excel 365
Error given - "PowerPoint Not found"
Sub ExcelRangeToPPT_new_now()
'prepareppt
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.IgnoreRemoteRequests = True
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
'Sheets("S19").Select
'Copy Range from Excel
Set rng = ThisWorkbook.ActiveSheet.Range("A1:q36")
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
Sheets("template").Select
Set rng = ThisWorkbook.ActiveSheet.Range("A1:q36")
instfile = "Noattach"
If ActFileName = False Then
'PowerPointApp.Activate
'PowerPointApp.Presentations.Add
'Set PP_File = PowerPointApp.ActivePresentation
Else
PowerPointApp.Activate
Set myPresentation = PowerPointApp.Presentations.Open(ActFileName)
End If
Set myPresentation = PowerPointApp.Presentations.Add
Set PP_File = PowerPointApp.ActivePresentation
adddd:
DoEvents
Set rng = ThisWorkbook.ActiveSheet.Range("A1:q36")
PowerPointApp.Visible = True
'Create a New Presentation
rrr:
err.Clear
Set mySlide = PP_File.Slides.Add(1, 12) '11 = ppLayoutTitleOnly
PP_File.Slides (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)
With PP_File.PageSetup
.SlideSize = ppSlideSizeCustom
.SlideWidth = 720
.SlideHeight = 528
.FirstSlideNumber = 1
.SlideOrientation = msoOrientationHorizontal
.NotesOrientation = msoOrientationVertical
End With
rng.Copy
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'Set position:
myShape.Left = 0
myShape.Top = 0
myShape.LockAspectRatio = msoFalse
myShape.HEIGHT = 528
myShape.WIDTH = 718
If instfile <> "Noattach" Then
Dim objPPTShape As Object
Set objPPTShape = PP_File.Slides(1).Shapes.AddOLEObject(Left:=100, Top:=100, WIDTH:=700, HEIGHT:=300, _
filename:=instfile, DisplayAsIcon:=True) 'OR Use , Filename:="E:\Documents and Settings\User\My Documents\abc.xlsm" instead of ClassName but not both
With objPPTShape
.Left = 475
.Top = 350
End With
Set objPPTShape = Nothing
End If
PowerPointApp.Visible = True
PowerPointApp.Activate
Application.CutCopyMode = False
PowerPointApp.PageSetup.SlideOrientation = msoOrientationHorizontal
sht = sht - 1
If sht = 1 Then Sheets("template").Select: GoTo ttre
instfile = "Noattach"
If sht = 2 Then Sheets("S2").Select: GoTo adddd
ttre:
Sheets("main").Select
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.IgnoreRemoteRequests = False
MsgBox "PPT Created Sucessfully.. Kindly review it before saving it.. "
Exit Sub
err:
Debug.Print "Error No.: " & err.Number & vbNewLine & vbNewLine & "Description: " & err.Description, vbCritical, "Error"
If err.Number = -2147467259 Then
MsgBox "Error Occured - Check if the Files to be embedded or the destination PPT is in the same folder as that of the Excel file..."
End If
If err.Number = 462 Then
Set PP_File = PowerPointApp.Presentations.Add
GoTo rrr
End If
If err.Number = 16 Then
MsgBox "Check if the Excel Files to be embedded is in the same folder.."
End
End If
End Sub
I have a similar issue with Excel and the On Error Resume Next code. Although I use it sparingly (I prefer to experience all the errors and handle them appropriately) it can be useful in some limited situations. I have found ways to rethink some code, in your for example you show this:
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
I would recode this piece as follows:
bPPOpen = GetObject(class:="PowerPoint.Application")
If bPPOpen Then
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
Else bPPOpen = False Then
Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
Endif
Using this technique you never have to attempt to SET the object unless you know it's available. Further, since you are not using a raised error you don't have to deal with some of the error 'clean up'.
Related
I try to apply a powerpoint table style from vba excel but i had an issue, someone can help to try how apply a style in table object ?
My macro work fine expect the style part ....
this code go to error 400 -- execution error --> Method 'table' of the object 'Shape' has failed
Set otbl = PPT_Shape.Table
This is a sample of my code here below
Sub ExcelRangeToPowerPoint()
'PURPOSE: Copy/Paste An Excel Range Into a New PowerPoint Presentation
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
Dim sPath As String
Dim project As String
Dim otbl As TableObject
'Set Title
project = Feuil1.Cells("2", "C")
'Set the template
sPath = "C:\Users\E049XXXX\OneDrive - XXX\XXX\"
'Copy Range from Excel
Set rng = ThisWorkbook.ActiveSheet.Range("A1:N34")
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If Err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
On Error GoTo 0
'Optimize Code
Application.ScreenUpdating = False
'Create a New Presentation
Set myPresentation = PowerPointApp.Presentations.Add
'Add a slide to the Presentation
Set mySlide = myPresentation.Slides.Add(1, 11) '11 = ppLayoutTitleOnly
'Add a slide to the Presentation
PowerPointApp.ActivePresentation.ApplyTemplate "C:\Users\E049XXXX\OneDrive - XXXX\Documents\XXXXX.thmx"
'Copy Excel Range
rng.Copy
'Paste to PowerPoint and position
mySlide.Shapes.PasteSpecial DataType:=0 '0 = ppPasteDefault
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'Set position:
myShape.Left = 66
myShape.Top = 152
'Add Title
Set myTitle = mySlide.Shapes.Title
myTitle.TextFrame.TextRange.Characters.Text = project
'Add style
Set PPT_Shape = myShape
Set otbl = PPT_Shape.Table
With otbl
.ApplyStyle "{C083E6E3-FA7D-4D7B-A595-EF9225AFEA82}", True
End With
'Make PowerPoint Visible and Active
PowerPointApp.Visible = True
PowerPointApp.Activate
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
I have got the below code to copy the image from range of cells of excel to PPT, but the image pasted on the PPT does is of different dimensions.
Can someone tell me how can I fix size of the image when pasted in PPT.
I am pasting my code below for your reference.
Private Sub CommandButton1_Click()
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
'Unhiding the sheets
Worksheets("Sheet4").Visible = xlSheetVisible
'Copy Range from Excel
Set rng = ThisWorkbook.ActiveSheet.Range("A1:C12")
'Create an Instance of PowerPoint
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
Err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If Err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
On Error GoTo 0
'Optimize Code
Application.ScreenUpdating = False
'Create a New Presentation
Set myPresentation = PowerPointApp.Presentations.Add
'Mupltiple Slides
'List of PPT Slides to Paste to
MySlideArray = Array(1, 2, 3)
'List of Excel Ranges to Copy from
MyRangeArray = Array(Sheet2.Range("A1:AB71"), Sheet1.Range("A1:AL70"), Sheet5.Range("A1:AE56"))
'Loop through Array data
For x = LBound(MySlideArray) To UBound(MySlideArray)
'Add a slide to the Presentation
Set mySlide = myPresentation.Slides.Add(1, 12) '12 = ppLayoutBlank 'https://learn.microsoft.com/en-us/office/vba/api/powerpoint.ppslidelayout
'Copy Excel Range
'rng.Copy
MyRangeArray(x).Copy
Application.Wait (Now + TimeValue("0:00:03"))
'Paste to PowerPoint and position
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile
Set myShape = mySlide.Shapes(mySlide.Shapes.count)
'Set position:
myShape.Left = 0
myShape.Top = 0
Next x
'Message Box
MsgBox ("Please is ready !!")
'Make PowerPoint Visible and Active
PowerPointApp.Visible = True
PowerPointApp.Activate
'Clear The Clipboard
Application.CutCopyMode = False
'Hiding the sheets back
Worksheets("Sheet4").Visible = xlSheetHidden
End Sub
I have finally been able to create this macro, which copying data from a specific range in excel and pasting it into an existing PPT.
Now I want to repeat this action for multiple slides, but instead of copy pasting this macro, again and again, is there any shorter code where I just change the range, destination slide, positioning and it creates the complete set.
Here is the existing code which is working fine:
'Macro1
Sub excelrangetopowerpoint_month()
Dim rng As Range
Dim powerpointapp As Object
Dim mypresentation As Object
Dim destinationPPT As String
Dim myshape As Object
Dim myslide As Object
Set rng = Worksheets("objectives").Range("m1")
On Error Resume Next
Set powerpointapp = CreateObject("powerpoint.application")
destinationPPT = ("C:\Users\OLX-Admin\Dropbox (Corporate Finance)\Naspers Monthly Reporting\Prep for call\From teams\FY2019\OLX Group Monthly Report_Sep'18_Macro.pptx")
powerpointapp.Presentations.Open (destinationPPT)
On Error GoTo 0
Application.ScreenUpdating = False
Set mypresentation = powerpointapp.ActivePresentation
Set myslide = mypresentation.Slides(1)
rng.Copy
myslide.Shapes.PasteSpecial DataType:=2 '2 = enhanced metafile
Set myshape = myslide.Shapes(myslide.Shapes.Count)
myshape.Left = 278
myshape.Top = 175
powerpointapp.Visible = True
powerpointapp.Activate
Application.CutCopyMode = False
End Sub
You could do it with another procedure like below. So you only have to duplicate one line for every copy to a slide.
Also note that your error handling was silent. That's a bad idea, because if an error occurs you just ignore it and you will never notice. Also the following code would not work properly. I changed that too.
Sub excelrangetopowerpoint_month()
Dim powerpointapp As Object
Set powerpointapp = CreateObject("powerpoint.application")
Dim destinationPPT As String
destinationPPT = ("C:\Users\OLX-Admin\Dropbox (Corporate Finance)\Naspers Monthly Reporting\Prep for call\From teams\FY2019\OLX Group Monthly Report_Sep'18_Macro.pptx")
On Error GoTo ERR_PPOPEN
Dim mypresentation As Object
Set mypresentation = powerpointapp.Presentations.Open(destinationPPT)
On Error GoTo 0
Application.ScreenUpdating = False
PasteToSlide mypresentation.Slides(1), Worksheets("objectives").Range("m1")
'duplicate this line for all slides/ranges
'PasteToSlide mypresentation.Slides(2), Worksheets("objectives").Range("m2")
powerpointapp.Visible = True
powerpointapp.Activate
Application.CutCopyMode = False
ERR_PPOPEN:
Application.ScreenUpdating = True 'don't forget to turn it on!
If Err.Number <> 0 Then
MsgBox "Failed to open " & destinationPPT, vbCritical
End If
End Sub
Private Sub PasteToSlide(mySlide As Object, rng As Range)
rng.Copy
mySlide.Shapes.PasteSpecial DataType:=2 '2 = enhanced metafile
Dim myShape As Object
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
myShape.Left = 278
myShape.Top = 175
End Sub
With this particular problem I can’t get the code to append the exported data from Access to Excel. I have created an simple Access database with some data shown on a form. After that it is possible to export the shown record to Excel using the code.
So far so good. But when I export the next record it overwrites the previous exported data on row one in Excel. I want the code to append to the next row and so on.
I have found some topics on how to append with “ActiveCell.Value” and “ActiveCell.Offset” but my knowledge is too limited to get it to work with the code. The moment I think I got it, VBE comes with errors. It seems I can't figure this out.
Private Sub Command15_Click()
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim oExcelWrSht As Object
Dim bExcelOpened As Boolean
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application") 'Bind to existing instance of Excel
If Err.Number <> 0 Then 'Could not get instance of Excel, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("excel.application")
bExcelOpened = False
Else 'Excel was already running
bExcelOpened = True
End If
On Error GoTo Error_Handler
oExcel.ScreenUpdating = False
oExcel.Visible = False 'Keep Excel hidden until we are done with our manipulation
'Set oExcelWrkBk = oExcel.Workbooks.Add() 'Start a new workbook
Set oExcelWrkBk = oExcel.Workbooks.Open("C:\test.xlsx") 'Open an existing Excel file
Set oExcelWrSht = oExcelWrkBk.Sheets(1) 'which worksheet to work with
'Start copying over your form values to the Excel Spreadsheet
'Cells(8, 3) = 8th row, 3rd column
oExcelWrSht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = Me.1
oExcelWrSht.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0) = Me.2
oExcelWrSht.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = Me.3
oExcelWrSht.Cells(Rows.Count, 4).End(xlUp).Offset(1, 0) = Me.4
oExcelWrSht.Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = Me.5
oExcelWrSht.Cells(Rows.Count, 6).End(xlUp).Offset(1, 0) = Me.6
oExcelWrSht.Cells(Rows.Count, 7).End(xlUp).Offset(1, 0) = Me.7
oExcelWrSht.Cells(Rows.Count, 8).End(xlUp).Offset(1, 0) = Me.8
oExcelWrSht.Cells(Rows.Count, 9).End(xlUp).Offset(1, 0) = Me.9
'... and so on ...
oExcelWrSht.Range("A1").Select 'Return to the top of the page
' oExcelWrkBk.Close True, sFileName 'Save and close the generated workbook
' 'Close excel if is wasn't originally running
' If bExcelOpened = False Then
' oExcel.Quit
' End If Error_Handler_Exit:
On Error Resume Next
oExcel.Visible = True 'Make excel visible to the user
Set oExcelWrSht = Nothing
Set oExcelWrkBk = Nothing
oExcel.ScreenUpdating = True
Set oExcel = Nothing
Exit Sub Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: Export2XLS" & vbCrLf & _
"Error Description: " & Err.Description _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit End Sub
I've tried this and no problems so assuming you have a reference to the right excel library can you see if this works?
Sub Test()
Dim oExcel As Excel.Application
Dim oExcelWrkBk As Excel.Workbook
Dim oExcelWrSht As Excel.Worksheet
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application")
If Err <> 0 Then
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("Excel.Application")
Else
On Error GoTo Error_Handler
End If
oExcel.ScreenUpdating = False
oExcel.Visible = False 'This is false by default anyway
Set oExcelWrkBk = oExcel.Workbooks.Open("C:\test.xlsx")
Set oExcelWrSht = oExcelWrkBk.Sheets(1)
oExcelWrSht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = "Test1"
oExcelWrSht.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0) = "Test2"
oExcelWrSht.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = "Test3"
oExcelWrSht.Range("A1").Select
oExcelWrkBk.Save
oExcel.ScreenUpdating = True
oExcel.Visible = True
Exit_Point:
Set oExcelWrSht = Nothing
Set oExcelWrkBk = Nothing
Set oExcel = Nothing
Exit Sub
Error_Handler:
MsgBox Err & " - " & Err.Description
GoTo Exit_Point
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`