Tuesday, December 24, 2024

VBA Word - Split Word Document of Large size and Many Pages

The following VBA code splits word document into two equal parts.
Sub SplitWordDocumentWithoutOpening()
    Dim appWord As Object
    Dim doc As Object
    Dim newDoc As Object
    Dim totalPages As Long
    Dim startPage As Long
    Dim splitPoint As Long
    Dim rng As Object
    Dim strDocumentPath As String
    Dim strOutputPath As String
    
    strDocumentPath = "G:\Word Documents\1\a1234.docx"
    strOutputPath = "G:\Word Documents"
    ' Create a Word application object (invisible)
    Set appWord = CreateObject("Word.Application")
    appWord.Visible = False

    ' Open the Word document
    Set doc = appWord.Documents.Open(strDocumentPath)
    
    ' Get total pages
    totalPages = doc.ComputeStatistics(wdStatisticPages)
    
    ' Define the split point (e.g., after half the pages)
    splitPoint = totalPages \ 2
    startPage = splitPoint + 1

    ' Copy pages from the split point to the end to a new document
    Set rng = doc.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Count:=startPage)
    Set rng = doc.Range(rng.Start, doc.Content.End)

    ' Create and save a new document for the second part
    Set newDoc = appWord.Documents.Add
    newDoc.Content.FormattedText = rng.FormattedText
    newDoc.SaveAs2 strOutputPath & "\Part2.docx"
    
    ' Remove the copied pages from the original document and save it
    rng.Delete
    doc.SaveAs2 strOutputPath & "\Part1.docx"

    ' Close documents and Word application
    newDoc.Close
    doc.Close
    appWord.Quit
    
    MsgBox "Document split successfully.", vbInformation
End Sub

No comments:

Post a Comment

Hot Topics