[VBA Powerpoint] How to check if a file exists in a directory already RRS feed

  • Question

  • Hi all,

    I have an add-in which saves out different packs of slides from a 'master' slides template. When you click on a macro button the macro automatically saves out the pack with the specified name of that related pack and uses text that has been entered on the first slide in a text box in the naming convention of the filename.

    All I am after is a simple way to stop users from saving over the same file if it has already been saved before. So I need some form of validation that checks to see whether the file exists...if it does then implement a version number to the filename and if it does not then save it like normal.

    Here is my code:

    Option Explicit

    Public Sub CreatePack(control As IRibbonControl)

    Dim packName As String
    Select Case control.Id
    Case "packbutton_B1"
    packName = "B1"
    Case "packbutton_B2"
    packName = "B2"
    Case "packbutton_TSD"
    packName = "TSD"
    End Select

    'Note: Attempt to remove characters that are not file-system friendly
    Dim Title As String
    If ActivePresentation.Slides(1).Shapes.Count >= 9 Then
    Title = Trim(ActivePresentation.Slides(1).Shapes(9).TextEffect.Text)
    If Title = "" Then MsgBox "Warning: A project title has not been entered on Slide 1."
    Title = "(Project Title Not Known)"
    MsgBox "The title slide has been removed, the project name cannot be detected."
    End If
    Title = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Title, "/", ""), "\", ""), ":", ""), "*", ""), "<", ""), ">", ""), "|", ""), """", "")

    Dim path As String
    path = ActivePresentation.path

    If MsgBox("This will produce a pack in a separate PowerPoint file. Before extracting the pack make sure you have implemented a version number otherwise your changes maybe overwritten." & vbCrLf & vbCrLf & "Your current file will remain open, and any pending changes will not be automatically saved.", vbOKCancel, "Slide Manager - Create Pack") = vbOK Then

    CopySlidesToBlankPresentation packName

    Application.ActivePresentation.SaveAs path & "\" & packName & " Slide Pack - " & Title, ppSaveAsOpenXMLPresentation



    End If

    End Sub

    Please note that the packs are currently being saved into the directory in which the master template is in. I want this to continue to happen, so the code needs to check within the directory that the master template is already in(which is where this .pptx file is being saved to as well).


    Wednesday, July 4, 2012 6:44 AM


  • I'm not a PowerPoint programmer but the following example works in Excel so I imagine it will be the same.

    Hope you can adapt it to your needs.

    If Dir(path & "\" & packname & " Slide Pack - " & Title) <> "" Then
        MsgBox "File exists"
        MsgBox "File does not exists"
    End If

    Regards, OssieMac

    Wednesday, July 4, 2012 7:01 AM