Jorge A
Jorge A

Reputation: 57

Split a word document into several pdf ones of 2 pages or more

I'm really not good at writing vba code, I'm more of an R and statistics guy, but I've been trying to automatize some mails that i have to manually write. All the info is from an excel I work with and with correspondence I can make several documents and then It would be ideal that the big document can be split into several pdf ones.

Please help.

I've tried several codes to make it work, the last one is this:

Sub Dividirdocumentos()
Dim iSplit As Long,
 iCount As Long,
 iLast As Long
Dim RngSplit As Range,
 StrDocName As String,
 StrDocExt As String
With ActiveDocument
iSplit = InputBox("El documento contiene " & .ComputeStatistics(wdStatisticPages) & " páginas." _
& vbCr & "¿Cuál es el número de páginas por el que quiere dividir?",
 "DividirDocumentos")
StrDocName = .FullName
StrDocExt = "." & Split(StrDocName, ".")(UBound(Split(StrDocName, ".")))
StrDocName = Left(StrDocName, Len(StrDocName) - Len(StrDocExt)) & "_"
For iCount = 0 To Int(.ComputeStatistics(wdStatisticPages) / iSplit)
If .ComputeStatistics(wdStatisticPages) > iSplit Then
iLast = iSplit
Else
iLast = .ComputeStatistics(wdStatisticPages)
End If
Set RngSplit = .GoTo(What:=wdGoToPage, Name:=iLast)
Set RngSplit = RngSplit.GoTo(What:=wdGoToBookmark, Name:="\page")
RngSplit.Start = .Range.Start
RngSplit.Cut
Documents.Add
Selection.Paste
ActiveDocument.SaveAs FileName:=StrDocName & iCount + 1 & StrDocExt, AddToRecentFiles:=False
ActiveWindow.Close
Next iCount
Set RngSplit = Nothing
'.Close Savechanges:=False
End With
End Sub

this one, allows me to split them into even pages, but they are not in pdf, neither i can choose which many pages is each document split. I have a document that has a section that i have to manually redact and each document is of variable lenght.

Upvotes: 1

Views: 81

Answers (1)

Jorge A
Jorge A

Reputation: 57

I was thinking about how I could develop the necessary code and I think I have found a useful answer. I share it with you in case you find yourself in the same situation as me:

I have created a code in VBA that allows a loop where at the beginning of each loop you can select the document you want to split , then you select the number of pages you want the document to split and from which page it starts. After that, create a pdf document with that content and save the word without that part of the document. Then it repeats the loop as many times as necessary until you enter a number of pages 0 which ends the loop.

Here is the code:

Sub ExtractPagesToPDF()
    'Declare variables
    Dim startPage As Integer
    Dim endPage As Integer
    Dim numPages As Integer
    Dim selectedDoc As Document
    Dim fileName As String
    Dim savePath As String
    
    'Prompt user to select Word document
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = False
        .Title = "Select the Word document to extract pages from"
        .Filters.Clear
        .Filters.Add "Word Documents", "*.docx;*.docm;*.doc;*.dotx;*.dotm;*.dot"
        .FilterIndex = 1
        
        If .Show = -1 Then 'if user selects a file
            fileName = .SelectedItems(1)
            'Get the path of the selected file
            savePath = Left(fileName, InStrRev(fileName, "\"))
        Else 'if user cancels
            MsgBox "No document selected.", vbCritical
            Exit Sub
        End If
    End With
    
    'Open the selected document
    Set selectedDoc = Documents.Open(fileName)
    
    'Start loop
    Do
        'Ask user to input number of pages to extract
        numPages = InputBox("Enter the number of pages to extract to PDF (or enter 0 to stop):")
        
        'Check if user wants to stop loop
        If numPages = 0 Then
            MsgBox "El proceso ha terminado con éxito", vbInformation
            Exit Do
        End If
        
        'Ask user to input start page number
        startPage = InputBox("Enter the starting page number:")
        
        'Calculate end page number
        endPage = startPage + numPages - 1
        
        'Extract pages to PDF
        With selectedDoc
            .ExportAsFixedFormat OutputFileName:=savePath & "ExtractedPages_" & startPage & "-" & endPage & ".pdf", ExportFormat:=wdExportFormatPDF, Range:=wdExportFromTo, From:=startPage, To:=endPage, OpenAfterExport:=False
        End With
        
    Loop
    
    'Close the document
    selectedDoc.Close savechanges:=False
End Sub

Upvotes: 1

Related Questions