My goal is to creat ppt via VBA. I have already the template in my desktop that i need to use. This part of the code is ok.
However I did not find how to select slides in the ppt. I try many ways and i get all the times error.
If someone could help me.
Option Explicit
Sub CreatePowerPoint()
Dim mySlide As PowerPoint.Slide
Dim myShapeRange As PowerPoint.Shape
Dim oPA As PowerPoint.Application
Dim oPP As PowerPoint.Presentation
Dim oPS As PowerPoint.SlideRange
Dim strTemplate As String
Dim rng As Range
strTemplate = "C:\Users\290866\Desktop\vba\PPT\Template.potx"
Set oPA = New PowerPoint.Application
oPA.Visible = msoTrue
oPA.Presentations.Open strTemplate, untitled:=msoTrue
If Not oPS Is Nothing Then Set oPS = Nothing
If Not oPP Is Nothing Then Set oPP = Nothing
If Not oPA Is Nothing Then Set oPA = Nothing
Err_PPT:
If Err <> 0 Then
MsgBox Err.Description
Err.Clear
Resume Next
End If
Set rng = ThisWorkbook.Sheets("Credit Recommendation").Range("B2:N59")
ActivePresentation.Slides (1)
rng.Copy
mySlide.Shapes.PasteSpecial (ppPasteBitmap)
Set myShapeRange = mySlide.Shapes(mySlide.Shapes.Count)
myShapeRange.LockAspectRatio = msoFalse
myShapeRange.Left = 20
myShapeRange.Top = 80
myShapeRange.Height = 400
myShapeRange.Width = 680
Application.CutCopyMode = False
End Sub
Thank you!!!
Here is your code modified to work. I explain the modifications below
Option Explicit
Sub CreatePowerPoint()
Dim mySlide As PowerPoint.Slide
Dim myShapeRange As PowerPoint.Shape
Dim oPA As PowerPoint.Application
Dim oPP As PowerPoint.Presentation
Dim oPS As PowerPoint.SlideRange
Dim strTemplate As String
Dim rng As Range
strTemplate = "C:\Users\290866\Desktop\vba\PPT\Template.potx"
Set oPA = New PowerPoint.Application
oPA.Visible = msoTrue
'changed this line to assign the new presentation to your variable
Set oPP = oPA.Presentations.Open(strTemplate, untitled:=msoTrue)
'If Not oPS Is Nothing Then Set oPS = Nothing
'If Not oPP Is Nothing Then Set oPP = Nothing
'If Not oPA Is Nothing Then Set oPA = Nothing
Err_PPT:
If Err <> 0 Then
MsgBox Err.Description
Err.Clear
Resume Next
End If
Set rng = ThisWorkbook.Sheets("sheet1").Range("B2:N59")
Set mySlide = oPP.Slides(1)
rng.Copy
mySlide.Shapes.PasteSpecial (ppPasteBitmap)
Set myShapeRange = mySlide.Shapes(mySlide.Shapes.Count)
myShapeRange.LockAspectRatio = msoFalse
myShapeRange.Left = 20
myShapeRange.Top = 80
myShapeRange.Height = 400
myShapeRange.Width = 680
Application.CutCopyMode = False
End Sub
You were declaring variables and never setting them equal to anything. I still did not see where oPS was ever used.
You received the ActiveX error because PowerPoint did not have an active presentation. It is always safer to work with your own objects rather than ActiveAnything within Office. So I set oPP equal to your new presentation and then used oPP rather than ActivePresentation
Also you never need to set things equal to nothing unless you're being picky about the order it happens. Everything declared in the Sub is set to nothing at the end of the sub.
Hope this helps!
Edit: Search and Replace
This is where I got the code, but I modified it to work as a callable Sub because I was calling it from different places many times:
'Find and Replace function
Sub FindAndReplace(sFind As String, sReplace As String, ByRef ppPres As PowerPoint.Presentation)
Dim osld As PowerPoint.Slide
Dim oshp As PowerPoint.Shape
Dim otemp As PowerPoint.TextRange
Dim otext As PowerPoint.TextRange
Dim Inewstart As Integer
For Each osld In ppPres.Slides
For Each oshp In osld.Shapes
If oshp.HasTextFrame Then
If oshp.TextFrame.HasText Then
Set otext = oshp.TextFrame.TextRange
Set otemp = otext.Replace(sFind, sReplace, , msoFalse, msoFalse)
Do While Not otemp Is Nothing
Inewstart = otemp.Start + otemp.Length
Set otemp = otext.Replace(sFind, sReplace, Inewstart, msoFalse, msoFalse)
Loop
End If
End If
Next oshp
Next osld
End Sub
You'll have to pass it the 2 strings and the Presentation object. It'll look like this in your Sub
FindAndReplace("FindMe","ReplaceWithThis", oPP)
Related
Goal: To get the Path and FileName of the PowerPoint Presentation in which my current Excel VBA is attached in as Object.
The screen-shot below might explain better what I mean:
This is the code I used to have to find the needed Presentation in case there are a few Presentations open at the same time (but I'm not able so far to get the Presentation in which I'm located in - and I don't want to pass the Presntation Name) :
Option Explicit
Sub UpdatePowerPoint(PowerPointFile)
Dim ppProgram As Object
Dim ppPres As Object
Dim CurOpenPresentation As Object
On Error Resume Next
Set ppProgram = GetObject(, "PowerPoint.Application")
On Error GoTo 0
If ppProgram Is Nothing Then
Set ppProgram = CreateObject("PowerPoint.Application")
Else
If ppProgram.Presentations.Count > 0 Then
For Each CurOpenPresentation In ppProgram.Presentations ' loop through all open presnetations (check Full Name: Path and name)
Dim CleanFullName As String * 1024
CleanFullName = Replace(CurOpenPresentation.FullName, "%20", " ") ' replace Sharepoint characters %20 with Space ("_")
If StrComp(PowerPointFile, CleanFullName, vbTextCompare) = 0 Then
Set ppPres = CurOpenPresentation
Exit For
End If
Next CurOpenPresentation
End If
End If
End Sub
Question: Am I missing an Excel/Office "Trick", which "ties" the Excel File somehow with the Presentation it's located in ? Maybe some other solution ?
Something along these lines
Sub T()
Dim ppProgram As PowerPoint.Application
Dim ppPresentation As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide
Dim ppShape As PowerPoint.Shape
Dim objExcel As Excel.Application
Set ppProgram = GetObject(, "PowerPoint.Application")
For Each ppPresentation In ppProgram.Presentations
For Each ppSlide In ppPresentation.Slides
For Each ppShape In ppSlide.Shapes
If ppShape.Type = msoEmbeddedOLEObject Then
Set objExcel = ppShape.OLEFormat.Object.Application
if objExcel.ActiveWorkbook.Name=activeworkbook.name then stop
Else
End If
Next ppShape
Next ppSlide
Next ppPresentation
End Sub
I'm trying to copy and paste a table consisting of shape from an Excel Sheet into a PowerPoint slide using VBA keeping its source formatting [].
I want to write directly on the tale on the slide after paste. Everything seems to work fine except the shape was not pasted into the table [].
Sub CreatePP()
Dim ppapp As PowerPoint.Application
Dim ppPres As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide
Dim ppTextBox As PowerPoint.Shape
Dim iLastRowReport As Integer
Dim sh As Object
Dim templatePath As String
On Error Resume Next
Set ppapp = GetObject(, "PowerPoint.Application")
On Error GoTo 0
'Let's create a new PowerPoint
If ppapp Is Nothing Then
Set ppapp = New PowerPoint.Application
End If
'Make a presentation in PowerPoint
If ppapp.Presentations.Count = 0 Then
Set ppPres = ppapp.Presentations.Add
ppPres.ApplyTemplate "C:\Users\luunt1\AppData\Roaming\Microsoft\Templates\Document Themes\themevpb.thmx"
End If
'Show the PowerPoint
ppapp.Visible = True
For Each sh In ThisWorkbook.Sheets
If sh.Name Like "E_KRI" Then
ppapp.ActivePresentation.Slides.Add ppapp.ActivePresentation.Slides.Count + 1, ppLayoutBlank
ppapp.ActiveWindow.View.GotoSlide ppapp.ActivePresentation.Slides.Count
Set ppSlide = ppapp.ActivePresentation.Slides(ppapp.ActivePresentation.Slides.Count)
ppSlide.Select
iLastRowReport = Range("B" & Rows.Count).End(xlUp).Row
Range("A1:J" & iLastRowReport).Copy
DoEvents
ppapp.CommandBars.ExecuteMso ("PasteExcelTableSourceFormatting")
Wait 3
With ppapp.ActiveWindow.Selection.ShapeRange
.Width = 700
.Left = 10
.Top = 75
.ZOrder msoSendToBack
End With
Selection.Font.Size = 12
'On Error GoTo NoFileSelected
AppActivate ("Microsoft PowerPoint")
Set ppSlide = Nothing
Set ppapp = Nothing
End If
Next
End Sub
Private Sub Wait(ByVal nSec As Long)
nSec = nSec + Timer
While nSec > Timer
DoEvents
Wend
End Sub
Rather than selecting the range of the table and pasting, it may solve your solution to instead paste the table object itself, so:
ActiveSheet.ListObjects(1).Copy 'Assuming it is the only table on the sheet. Adjust this code as needed for your specific case
I'm current using vba to automate the creation of a ppt report. I need to copy charts from excel and paste into ppt. I successfully used the ExecuteMso "PasteExcelChartSourceFormatting" to paste the chart in, which I need to use so I can paste while keeping the source formatting and embedding the workbook, but I keep getting an error after that when my code tries to reposition the chart in ppt.
See code:
Sub Update()
Dim ppApp As PowerPoint.Application
Dim ppPres As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide
Set ppApp = New PowerPoint.Application
ppApp.Visible = True
ppApp.Activate
Set ppPres = ppApp.Presentations.Open("C:\Users\ashah\Documents\Advisory.pptx")
ppPres.Slides(1).Shapes(7).Delete
Sheet1.ChartObjects("Chart 24").Chart.ChartArea.Copy
ppPres.Slides(1).Select
DoEvents
ppApp.CommandBars.ExecuteMso "PasteExcelChartSourceFormatting"
ppApp.CommandBars.ReleaseFocus
DoEvents
ppPres.Slides(1).Shapes(7).Left = _
(ppPres.PageSetup.SlideWidth / 2) - (ppPres.Slides(1).Shapes(7).Width / 2)
ppPres.Slides(1).Shapes(7).Top = 77
End Sub
I get a run-time error '--2147188160 (80048240)', method 'Item' of object 'Shapes' failed. The debug highlights the last few lines of my code.
Any advice would be greatly appreciated!
I know this is a little late to the game, but I used this post to try and answer the same problem I was having. And I wanted to pay it forward when I found the solution.
Now my code is a little different because I'm creating a new slide for every chart in my excel worksheet, but I too need to keep the source formatting.
Dim PowerPointApp As Object
Dim CurrentSlide As Object
Dim PowerPointDoc As Object
Dim xChart As ChartObject
Dim wb As Workbook
Dim ws As Worksheet
Dim Chart As ChartObject
Dim Sheet As Worksheet
Dim x As Long
Set wb = ActiveWorkbook
Set ws = wb.ActiveSheet
Set PowerPointApp = CreateObject("Powerpoint.Application")
Set PowerPointDoc = PowerPointApp.Presentations.Add(msoTrue)
PowerPointApp.Visible = True
For Each Chart In ws.ChartObjects
PowerPointApp.ActivePresentation.Slides.Add
PowerPointApp.ActivePresentation.Slides.count + 1, 12
Set CurrentSlide = PowerPointDoc.Slides(PowerPointDoc.Slides.count)
CurrentSlide.Select
Chart.Copy
PowerPointApp.CommandBars.ExecuteMso "PasteExcelChartSourceFormatting"
'**********************************
Do
DoEvents
Loop Until CurrentSlide.Shapes.count > 0
'**********************************
Next Chart
The "Do While Loop" has helped avoid this error. It does take some time for the macro to finish depending on how many charts you have.
Can you try this, slightly different method
Sub Update()
Dim ppApp As PowerPoint.Application
Dim ppPres As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide
Set ppApp = New PowerPoint.Application
ppApp.Visible = True
ppApp.Activate
Set ppPres = ppApp.Presentations.Open("C:\Users\ashah\Documents\Advisory.pptx")
Set ppSlide = ppPres.Slides(1)
ppSlide.Shapes(7).Delete
Sheet1.ChartObjects(1).Chart.ChartArea.Copy
ppSlide.Shapes.Paste.Select
With ppPres.Windows(1).Selection.ShapeRange
.Left = (ppPres.PageSetup.SlideWidth / 2) - (.Width / 2)
.Top = 77
End With
End Sub
UPDATE:
I split this into two subs. Can you give this a try
Sub Update()
Dim ppApp As PowerPoint.Application
Dim ppPres As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide
Set ppApp = New PowerPoint.Application
ppApp.Visible = True
ppApp.Activate
Set ppPres = ppApp.presentations.Open("C:\Users\ashah\Documents\Advisory.pptx")
Set ppSlide = ppPres.Slides(1)
ppSlide.Shapes(7).Delete
Call CopyAndPasteChart(ppApp, ppSlide)
With ppSlide.Shapes(ppSlide.Shapes.Count)
.Left = (ppPres.PageSetup.SlideWidth / 2) - (.Width / 2)
.Top = -77
End With
ppApp.CommandBars.ReleaseFocus
End Sub
Sub CopyAndPasteChart(ppApp As PowerPoint.Application, ppSlide As PowerPoint.Slide)
Sheet1.ChartObjects(1).Chart.ChartArea.Copy
ppApp.CommandBars.ExecuteMso ("PasteExcelChartSourceFormatting")
End Sub
You could edit the CopyAndPasteChart Sub a bit more if you fancied to make it usable in more situations.
I have created a code with vba which copy data from excel sheet and paste the same as picture in powerpoint slide, but its not working exactly as per my need.
It should copy data from each worksheets and paste it in a given powerpoint slide worksheet wise. Measn worksheet 1 data should be copied in slide 1 followed by worksheet 2 data in slide 2 and so on and at the end it should save the created ppt file.
But my code is copying and pasting all worksheets data overlaping each other in all the slides of the powerpoint.
Since i am new to vba i am not sure where i am going wrong with the below code:
Sub WorkbooktoPowerPoint()
Dim xlwksht As Worksheet
Dim MyRange As String
Dim MyRange1 As String 'Define another Range
Dim MyTitle As String
Dim oPPTApp As PowerPoint.Application
Dim oPPTShape As PowerPoint.Shape
Dim oPPTFile As PowerPoint.Presentation
Dim SlideNum As Integer
Dim oSlide As Slide
Dim strPresPath As String, strExcelFilePath As String, strNewPresPath As String
strPresPath = "C:\Users\FYI\PPT1.pptx"
strNewPresPath = "C:\Users\FYI\new1.pptx"
Set oPPTApp = CreateObject("PowerPoint.Application")
oPPTApp.Visible = msoTrue
Set oPPTFile = oPPTApp.Presentations.Open(strPresPath)
For Each oSlide In oPPTFile.Slides
i = oSlide.SlideNumber
oSlide.Select
MyRange = "B2:B5"
MyRange1 = "B8:B11"
For Each xlwksht In ActiveWorkbook.Worksheets
xlwksht.Select Application.Wait(Now + TimeValue("0:00:1"))
xlwksht.Range(MyRange).CopyPicture Appearance:=xlScreen, Format:=xlPicture
oSlide.Shapes.Paste.Select
oPPTApp.ActiveWindow.Selection.ShapeRange.Align msoAlignTops, True
oPPTApp.ActiveWindow.Selection.ShapeRange.Top = 65
oPPTApp.ActiveWindow.Selection.ShapeRange.Left = 7.2
oPPTApp.ActiveWindow.Selection.ShapeRange.Width = 400
xlwksht.Range(MyRange1).CopyPicture Appearance:=xlScreen, Format:=xlPicture
oSlide.Shapes.Paste.Select
oPPTApp.ActiveWindow.Selection.ShapeRange.Align msoAlignBottoms, True
oPPTApp.ActiveWindow.Selection.ShapeRange.Top = 250
oPPTApp.ActiveWindow.Selection.ShapeRange.Left = 7.2
oPPTApp.ActiveWindow.Selection.ShapeRange.Width = 400
Next xlwksht
Next
oPPTApp.Activate
oPPTFile.SaveAs strNewPresPath
oPPTFile.Close
oPPTApp.Quit
Set oPPTShape = Nothing
Set oPPTFile = Nothing
Set oPPTApp = Nothing
MsgBox "Presentation Created", vbOKOnly + vbInformation
End Sub
Please give this a shot. The main change is that I removed the For Each loop. You are already looping through the slides of the deck and can use the slide number to reference the Excel worksheet (they are numbered, as well). It was creating a mess, now it runs smoothly.
Sub WorkbooktoPowerPoint()
Dim xlwksht As Worksheet
Dim MyRange As String
Dim MyRange1 As String 'Define another Range
Dim oPPTApp As PowerPoint.Application
Dim oPPTShape As PowerPoint.Shape
Dim oPPTFile As PowerPoint.Presentation
Dim SlideNum As Integer
Dim oSlide As Slide
Dim strPresPath As String, strExcelFilePath As String, strNewPresPath As String
strPresPath = "C:\Users\FYI\PPT1.pptx"
strNewPresPath = "C:\Users\FYI\new1.pptx"
Set oPPTApp = CreateObject("PowerPoint.Application")
oPPTApp.Visible = msoTrue
Set oPPTFile = oPPTApp.Presentations.Open(strPresPath)
For Each oSlide In oPPTFile.Slides
i = oSlide.SlideNumber
' The following line was added after the OPs follow-up
If i > ActiveWorkbook.Sheets.Count Then Exit For
oSlide.Select
MyRange = "B2:B5"
MyRange1 = "B8:B11"
With ActiveWorkbook.Sheets(i)
.Range(MyRange).CopyPicture Appearance:=xlScreen, Format:=xlPicture
oSlide.Shapes.Paste.Select
With oPPTApp
.ActiveWindow.Selection.ShapeRange.Align msoAlignTops, True
.ActiveWindow.Selection.ShapeRange.Top = 65
.ActiveWindow.Selection.ShapeRange.Left = 7.2
.ActiveWindow.Selection.ShapeRange.Width = 400
End With
.Range(MyRange1).CopyPicture Appearance:=xlScreen, Format:=xlPicture
oSlide.Shapes.Paste.Select
With oPPTApp
.ActiveWindow.Selection.ShapeRange.Align msoAlignBottoms, True
.ActiveWindow.Selection.ShapeRange.Top = 250
.ActiveWindow.Selection.ShapeRange.Left = 7.2
.ActiveWindow.Selection.ShapeRange.Width = 400
End With
End With
Next
oPPTApp.Activate
oPPTFile.SaveAs strNewPresPath
oPPTFile.Close
oPPTApp.Quit
Set oPPTShape = Nothing
Set oPPTFile = Nothing
Set oPPTApp = Nothing
MsgBox "Presentation Created", vbOKOnly + vbInformation
End Sub
I am trying to create charts and tables in excel and then copy them to slides in powerpoint all through a PowerPoint VBA macro. I have the charts and tables created but I am having an issue with copying and pasting them over. I am not familiar with the syntax to do so. Any help would be greatly appreciated as I am new to PowerPoint VBA.
Sub GenerateVisual()
Dim dlgOpen As FileDialog
Dim folder As String
Dim excelApp As Object
Dim xlWorkBook As Object
Dim xlWorkBook2 As Object
Dim PPT As Presentation
Dim Name1 As String
Dim Name2 As String
Set PPT = ActivePresentation
Set excelApp = CreateObject("Excel.Application")
excelApp.Visible = True
Set xlWorkBook = excelApp.workbooks.Open("C:\Users\wzawisa\Downloads\MarketSegmentTotals.xls")
xlWorkBook.Sheets("MarketSegmentTotals").Activate
xlWorkBook.ActiveSheet.Shapes.AddChart.Select
xlWorkBook.ActiveChart.ChartType = xlColumnClustered
xlWorkBook.ActiveChart.SetSourceData Source:=xlWorkBook.ActiveSheet.Range("MarketSegmentTotals!$A$1:$F$2")
xlWorkBook.ActiveChart.Legend.Delete
xlWorkBook.ActiveChart.SetElement (msoElementChartTitleAboveChart)
xlWorkBook.ActiveChart.SetElement (msoElementDataLabelCenter)
xlWorkBook.ActiveChart.ChartTitle.Text = "DD Ready by Market Segment"
xlWorkBook.ActiveSheet.ListObjects.Add
xlWorkBook.ActiveSheet.ChartObjects(1).Select 'My attempt to copy them over but it doesnt work
PPT.ActiveWindow.View.Paste
End Sub
This sub will get you on your way. It needs some tweaks but this can copy over a range into a PPT:
Public Sub RangeToPresentation(sheetName, NamedRange)
Dim CopyRng As Range
Set CopyRng = Sheets(sheetName).Range(NamedRange)
Dim ppApp As Object
Dim ppPres As Object
Dim PPSlide As Object
If Not TypeName(CopyRng) = "Range" Then
MsgBox "Please select a worksheet range and try again.", vbExclamation, _
"No Range Selected"
Else
Set ppApp = GetObject(, "Powerpoint.Application")
Set ppPres = ppApp.ActivePresentation
ppApp.ActiveWindow.ViewType = ppViewNormal
Dim longSlideCount As Long
' Determine how many slides are in the presentation.
longSlideCount = ppPres.Slides.Count
With ppPres
' Insert a slide at the end of the presentation
Set PPSlide = ppPres.Slides.Add(longSlideCount + 1, ppLayoutBlank)
End With
' Select the last (blank slide)
longSlideCount = ppPres.Slides.Count
ppPres.Slides(longSlideCount).Select
Set PPSlide = ppPres.Slides(ppApp.ActiveWindow.Selection.SlideRange.SlideIndex)
CopyRng.CopyPicture Appearance:=xlScreen, _
Format:=xlBitmap
' Paste the range
PPSlide.Shapes.Paste.Select
'Set the image to lock the aspect ratio
ppApp.ActiveWindow.Selection.ShapeRange.LockAspectRatio = msoTrue
'Set the image size slightly smaller than width of the PowerPoint Slide
ppApp.ActiveWindow.Selection.ShapeRange.Width = ppApp.ActivePresentation.PageSetup.SlideWidth - 10
ppApp.ActiveWindow.Selection.ShapeRange.Height = ppApp.ActivePresentation.PageSetup.SlideHeight - 10
'Shrink image if outside of slide borders
If ppApp.ActiveWindow.Selection.ShapeRange.Width > 700 Then
ppApp.ActiveWindow.Selection.ShapeRange.Width = 700
End If
If ppApp.ActiveWindow.Selection.ShapeRange.Height > 600 Then
ppApp.ActiveWindow.Selection.ShapeRange.Height = 600
End If
' Align the pasted range
ppApp.ActiveWindow.Selection.ShapeRange.Align msoAlignCenters, True
ppApp.ActiveWindow.Selection.ShapeRange.Align msoAlignMiddles, True
' Clean up
Set PPSlide = Nothing
Set ppPres = Nothing
Set ppApp = Nothing
End If
End Sub