Home > Software design >  PPT VBA to open another PPT failed
PPT VBA to open another PPT failed

Time:12-22

I was trying to use VBA to open another PPT and copy the 2 pages in it to the end of my current ppt. I used Presentation.Open to open the ppt, however, it gave me an error at this line: Presentations.Open (ppt_SourceFile): Run-time error '-2147467259(80004005)': Method 'Open' of object 'Presentations' failed. Can anyone please help me understand what was wrong? Thank you in advance!!!

Sub copyFromPPT()
Dim slideCount As Integer
Dim sourcePath as string, ppt_SourceFile As String, pptSource As String, thisPresentation As String

    'Copy and paste the pages at the end
    thisPresentation = ActivePresentation.Name
    slideCount = ActivePresentation.Slides.Count
    
    'Open ppt file
    sourcePath = ActivePresentation.Path
    ppt_SourceFile = sourcePath & "\CFTC Reg Reporting*.pptx"
    
    Presentations.Open (ppt_SourceFile)
    pptSource = ActivePresentation.Name
    
    'Copy the 1st slide of source ppt to end of this slide
    ActivePresentation.Slides(1).Copy
    Presentations(thisPresentation).Slides.paste
    slideCount = ActivePresentation.Slides.Count
    
    'Copy the 2nd slide of source ppt to end of this slide
    Presentations(pptSource).Slides(2).Copy
    Presentations(thisPresentation).Slides.paste
    
    'Close source ppt file
    Presentations(pptSource).Close
    ActivePresentation.Save
End Sub

CodePudding user response:

If there's only one matching file in the folder you can do something like this:

Sub copyFromPPT()
    Dim thisPres As Presentation, sourcePres As Presentation, f
    Dim sourcePath As String

    Set thisPres = ActivePresentation
    
    sourcePath = thisPres.Path & "\"
    f = Dir(sourcePath & "CFTC Reg Reporting*.pptx") 'see if there's a file...
    If Len(f) = 0 Then
        MsgBox "No matching file found", vbExclamation
        Exit Sub
    End If
    
    Set sourcePres = Presentations.Open(sourcePath & f) 'Open ppt file and get a reference
    
    sourcePres.Slides(1).Copy
    thisPres.Slides.Paste     'you can add a paste position here, or leave blank to paste to the end...
    sourcePres.Slides(2).Copy
    thisPres.Slides.Paste
    
    sourcePres.Close
    thisPres.Save
End Sub
  • Related