-3

I have currently written an Excel VBA code which creates 40+ PowerPoint Slides. However, while running this code PowerPoint crashes after creating 22 slides. This issue only occurs when the VBA code is run at one go. Because, when I try to run the same code line by line it runs successfully till end.

For me this is something weird. Do we have any suggestion for this problem ?

=> My code till creation of slide 2 is listed below (thereafter it create the other slides one after another till 43rd Slide)

Regards, Alok

Sub test25()

Dim pApp  As PowerPoint.Application
Dim pPres As PowerPoint.Presentation
Dim pSlid As PowerPoint.Slide

Set pApp = New PowerPoint.Application

pApp.Visible = True
pApp.Activate

Set pPres = pApp.Presentations.Open("C:\.....\Template.pptx")

pPres.Slides(1).Select
Sheets("S01").Select
    ActiveSheet.Range("A1:P27").Select
    ActiveSheet.Shapes.SelectAll
    Selection.copy
pPres.Slides(1).Shapes.PasteSpecial DataType:=wdPasteText

pPres.Slides(2).Duplicate
pPres.Slides(2).Select
Sheets("S02").Select
    ActiveSheet.Range("A1:P27").Select
    ActiveSheet.Shapes.SelectAll
    Selection.copy
pPres.Slides(2).Shapes.PasteSpecial DataType:=wdPasteText


End Sub
Alok Nagar
  • 39
  • 2
  • 8

1 Answers1

0

I see multiple potential issues, some of which are just code improvements.

On the line:

pPres.Slides(2).Duplicate

You are referring to slide 2, but you have not yet created slide 2 (as this is the line that creates it). Change this to:

pPres.Slides(1).Duplicate

I don't see how your code is running, even line by line, without that...unless 'template.pptx' already has all of the slides (in which case, why are you duplicating? I assumed 'template.pptx only contained the first slide)

Initially I suspected a race condition, but typically VBA handles these well. To be sure, and just general good practice, you may want to use a variable to refer to the current slide, instead of just a number (you already have the variable declared)

Set pSlid = pPres.Slides(1)
Sheets("S01").Select
    ActiveSheet.Range("A1:P27").Select
    ActiveSheet.Shapes.SelectAll
    Selection.copy
pSlid.Shapes.PasteSpecial DataType:=wdPasteText

Set pSlid = pSlid.Duplicate
...

Also for your own convenience, you way want to look into using a loop, like:

Set pSlid = pPres.Slides(1)
For i = 1 to 43
  Sheets("S" & Format(CStr(i), "00")).Select
    ActiveSheet.Range("A1:P27").Select
    ActiveSheet.Shapes.SelectAll
    Selection.copy
  pSlid.Shapes.PasteSpecial DataType:=wdPasteText

  Set pSlid = pSlid.Duplicate
Next
  • Thanks for your comments they are very useful. However, I have template.xlsx which already contains more than 1 slides and they need to be referred as per the data which is required to paste on that certain slide. That is the reason sometimes I directly select the slide or sometimes I duplicate that. I am going to your use your suggestion. I will keep you posted about the same – Alok Nagar Apr 30 '18 at 08:59