Hello there,
I'm happy to hear it worked fine your issue might be related to how the macro is navigating through the document to find the "Data_Start" sections so I've proposed an update code you can access below:
Sub SplitDocumentByHeading()
Dim doc As Document
Dim rng As Range
Dim sectionCount As Integer
Dim sectionTitle As String
Dim newDoc As Document
Dim savePath As String
' Set the path where the new documents will be saved
savePath = ThisDocument.Path & Application.PathSeparator
' Initialize variables
Set doc = ActiveDocument
Set rng = doc. Content
sectionCount = 0
' Find the first "Data_Start" occurrence
If rng. Find.Execute(FindText:="Data_Start") Then
Do
' Get the section title (assuming it's in the line before "Data_Start")
sectionTitle = rng. Previous(wdParagraph). Range.Text
' Increment section count
sectionCount = sectionCount + 1
' Set range to the content between this "Data_Start" and the next one
Set rng = doc. Range(rng. End, doc. Content.End)
If rng. Find.Execute(FindText:="Data_Start") Then
Set rng = doc. Range(rng. Start, rng. Start)
Else
Set rng = doc. Range(rng. Start, doc. Content.End)
End If
' Copy the section content to a new document
Set newDoc = Documents.Add
doc. Range(rng. Start, rng. End - 1). Copy
newDoc.Range.Paste
' Save the new document with a suffix and close it
newDoc.SaveAs2 FileName:=savePath & "Section_" & sectionCount & "_" & Trim(sectionTitle) & ".docx"
newDoc.Close False
' Move to the end of the current section
rng. Collapse Direction:=wdCollapseEnd
Loop While rng. Find.Execute(FindText:="Data_Start")
MsgBox "Document split completed."
Else
MsgBox "No 'Data_Start' found in the document."
End If
' Clean up
Set doc = Nothing
Set rng = Nothing
Set newDoc = Nothing
End Sub
This approach should help ensure that each "Data_Start" section is processed and saved into separate documents as intended and like yourself I'm still new to VBA so don't worry!
I hope these following solutions have been of assistance and should you have anymore problems please do not hesitate to contact me again in the future.
Give back to the Community. Help the next person who has this issue by indicating if this reply solved your problem. Click Yes or No below.