View Single Post
 
Old 01-23-2020, 09:12 AM
kalton kalton is offline Windows 10 Office 2016
Novice
 
Join Date: Jan 2020
Posts: 1
kalton is on a distinguished road
Default Delete last page of .docx and then save as .pdf for all the files in a folder

Currently, I am trying to write something in word VBA to delete the last page for a document and then save it as a pdf before moving onto the next one. The macro runs for about ~15 documents before giving the error runtime error 5904: cannot edit range. This is a little concerning as I have ~350 documents that need to have this done to them.

Does anyone have any ideas on what to do?

Code:
Sub ConvertWordsToPdfs()

    Dim directory As String
    directory = "C:\Users\kalton\Documents\TEST" ' The starting directory

    Dim fso, folder, files
    Set fso = CreateObject("Scripting.FileSystemObject")

    Set folder = fso.GetFolder(directory)
    Set files = folder.files

    For Each File In files

        Dim newName As String
        newName = Replace(File.Path, ".docx", ".pdf")

        Documents.Open FileName:=File.Path, _
            ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
            PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
            WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
            wdOpenFormatAuto, XMLTransform:=""

            DeleteLastPage

        ActiveDocument.ExportAsFixedFormat OutputFileName:=newName, _
            ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
            wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
            Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
            CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
            BitmapMissingFonts:=True, UseISO19005_1:=False
        ActiveDocument.Close savechanges:=False

    Next

End Sub

Sub DeleteLastPage()
Dim lngCharacters As Long
Dim r As Range

With ActiveDocument
    lngCharacters = .GoTo(wdGoToPage, wdGoToLast).Start
    Set r = .Range(lngCharacters - 1, .Range.End)
    r.Delete
End With
End Sub

Last edited by macropod; 01-23-2020 at 09:19 PM. Reason: Added code tags
Reply With Quote