Hi Everyone,
Looking to split a word document using the header1 feature. However I can’t use the split that built into work due to the document having tables in it. So I went down the vba route. However I keep getting errors. I’m wanting to split via header 1 tag and then use the text in header 1 as the file name.
Whats wrong with my code?
Thanks in advance
Sub SplitDocumentByHeading1()
Dim originalDoc As Document
Dim newDoc As Document
Dim para As Paragraph
Dim rng As Range
Dim title As String
Dim saveFolderPath As String
' Set the folder path to save the new documents
saveFolderPath = "\\SAM-FS-02\staffhome$\jwalsh\MCAS"
' Set the original document
Set originalDoc = ActiveDocument
' Loop through each paragraph in the document
For Each para In originalDoc.Paragraphs
' Check if the paragraph is a Heading 1
If para.Style = "Heading 1" Then
' Get the Heading 1 text as the document title
title = para.Range.Text
' Create a new document
Set newDoc = Documents.Add
newDoc.Range.FormattedText = para.Range.FormattedText
' Set the range to include the entire new document
Set rng = newDoc.Range
' Find and remove the page breaks in the new document
With rng.Find
.Text = "^m"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
' Save and close the new document in the specified folder with the title as the file name
newDoc.SaveAs2 saveFolderPath & title & ".docx"
newDoc.Close
' Reset the range to the original document
Set rng = originalDoc.Range
End If
Next para
' Clean up objects
Set newDoc = Nothing
Set originalDoc = Nothing
' Notify the user when the splitting process is complete
MsgBox "Document has been split by Heading 1."
End Sub