Copy headings and Contents to new document - vba

I am trying to create an audiobook with multiple tracks so it's easy to navigate through the book while I'm doing other things like driving or working out. The only way I can think to do this is to have each heading and its contents in its own separate document. I've been using the select headings and content option but there's no shortcut for this option. you must click it each time.
everything I've looked at online doesn't do what I want.
is there a way to select each heading and contents copy that to a new document, save it as TXT so each of the heading and content is in its own document?
Select Heading and Content

You could use a macro like the following to split the document at the Heading1 level:
Sub SplitDocumentByHeading()
Application.ScreenUpdating = False
Dim DocSrc As Document, DocTgt As Document, Rng As Range, i As Long
Dim StrTmplt As String, StrNm As String, StrEx As String, lFmt As Long
Set DocSrc = ActiveDocument
With DocSrc
StrTmplt = .AttachedTemplate.FullName
StrNm = Split(.FullName, ".doc")(0)
StrEx = Split(.FullName, ".doc")(1)
lFmt = .SaveFormat
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Style = wdStyleHeading1
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found
i = i + 1
Set Rng = .Duplicate.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set DocTgt = Documents.Add(Template:=StrTmplt, Visible:=False)
With DocTgt
.Range.FormattedText = Rng.FormattedText
.SaveAs2 FileName:=StrNm & "_" & Format(i, "00") & ".txt", Fileformat:=wdFormatText, AddToRecentFiles:=False
.Close
End With
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End With
Set DocTgt = Nothing: Set Rng = Nothing: Set DocSrc = Nothing
Application.ScreenUpdating = True
End Sub
Rather more complex code would be required to split it at the sub-heading level.

Related

How to find table column, then move down and replace the cell's content IF it is "N/A"

I have almost 1,800 Word documents that have about 8 pages with unique data in tables. We were just informed that the data we were given for some of those tables is inaccurate and needs to be changed from "N/A" to "0.0%". As "N/A" is used a lot in the document, I unfortunately cannot just find/replace that text.
Using this thread (Macro to find in Word table for specific string in a cell and move x cell left, check isnumeric then set typography on down x cell in the same column) I was able to adjust the code below to find the column header (On-Time Completion Rate) and move to the adjacent cells to update them. However, since this column is for percentages, the IsNumeric code is changing any data it finds due to the percentage symbol.
Is there a way to do the same but instead of using IsNumeric (since it does not work for percentages) check the value in the cell and if it finds "N/A" change it to "0.0%"? This would then need to be repeated for two more tables, with one table have four rows to look through.
Thank you in advance for any help you can offer!
Screenshot of table
Sub Demo()
Application.ScreenUpdating = False
Dim r As Long, c As Long
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "On-time Completion Rate" 'Column Header'
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If .Information(wdWithInTable) = True Then
r = .Cells(1).RowIndex
c = .Cells(1).ColumnIndex
With .Tables(1)
If Not IsNumeric(Split(.Cell(r + 1, c).Range.Text, vbCr)(0)) Then .Cell(r + 1, c).Range.Text = "0.0%"
If Not IsNumeric(Split(.Cell(r + 2, c).Range.Text, vbCr)(0)) Then .Cell(r + 2, c).Range.Text = "0.0%"
End With
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub
Try this:
Sub Demo()
Application.ScreenUpdating = False
Dim r As Long, c As Long
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "On-time Completion Rate" 'Column Header'
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If .Information(wdWithInTable) = True Then
r = .Cells(1).RowIndex
c = .Cells(1).ColumnIndex
With .Tables(1)
If Split(.Cell(r + 1, c).Range.Text, vbCr)(0) = "N/A" Then .Cell(r + 1, c).Range.Text = "0.0%"
If Split(.Cell(r + 2, c).Range.Text, vbCr)(0) = "N/A" Then .Cell(r + 2, c).Range.Text = "0.0%"
End With
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub
If all instances of N/A in the tables are to be replaced, the following would be more efficient:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "On-time Completion Rate"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
.Duplicate.Tables(1).Range.Find.Execute FindText:="N/A", ReplaceWith:="0.0%", Wrap:=wdFindStop, Replace:=wdReplaceAll
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub
Extending this to process a whole folder of documents, you could use code like:
Sub UpdateDocuments()
Application.ScreenUpdating = False
Dim strFolder As String, strFile As String, strDocNm As String, wdDoc As Document
strDocNm = ActiveDocument.FullName: strFolder = GetFolder
If strFolder = "" Then Exit Sub
strFile = Dir(strFolder & "\*.docx", vbNormal)
While strFile <> ""
If strFolder & "\" & strFile <> strDocNm Then
Set wdDoc = Documents.Open(FileName:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "On-time Completion Rate"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
.Duplicate.Tables(1).Range.Find.Execute FindText:="N/A", ReplaceWith:="0.0%", Wrap:=wdFindStop, Replace:=wdReplaceAll
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
.Close SaveChanges:=True
End With
End If
strFile = Dir()
Wend
Set wdDoc = Nothing
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
To extend the code even further to process documents in sub-folders, see: https://www.msofficeforums.com/47785-post14.html
To save the updated documents as PDFs, insert:
.SaveAs FileName:=Split(.FullName, ".doc")(0) & ".pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False
before:
.Close SaveChanges:=True

Copy entire page to a text document with find?

I have found many examples of macros to copy selected pages to a new document, however, I am unable to find any examples of macros that use find and replace to locate a word, and copy the entire page containing that word to a new word document or notepad.
Sub PageGrabber()
Dim doc As Word.Document, rng As Word.Range
On Error GoTo ERRORHANDLER
Set doc = ActiveDocument
Set rng = doc.Content
Set rng = doc.Content
With rng.Find
.Text = "help"
.Replacement.Text = " "
.MatchWildcards = False
.Wrap = wdFindStop
.Format = False
.Forward = True
While .Execute
ActiveDocument.Bookmarks("\page").Range.Copy
Documents.Open FileName:="C:\test.docx"
Selection.Paste
rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
Wend
End With
ERRORHANDLER:
If Err.Number <> 0 Then
MsgBox Err.Number & vbCr & Err.Description, vbCritical
Err.Clear
Else
MsgBox "Action Complete"
End If
End Sub
I was attempting to use while .execute during the find to then grab the ActiveDocument.Bookmarks("\page").Range.Copy object and paste it onto a seperate document, it resulted in the first page being copied and nothing else.
If anyone has a link to an example or some useful advice to get this to happen it would be appreciated, thanks.
For example:
Sub PageGrabber()
Application.ScreenUpdating = False
Dim DocSrc As Document, DocTgt As Document
Set DocSrc = ActiveDocument
With DocSrc.Range
With .Find
.Text = "help"
.Replacement.Text = " "
.MatchWildcards = False
.Wrap = wdFindStop
.Format = False
.Forward = True
.Execute
End With
If .Find.Found = True Then
Set DocTgt = Documents.Open(FileName:="C:\test.docx", AddToRecentFiles:=False, Visible:=False)
DocTgt.Range.FormattedText = .Bookmarks("\page").Range.FormattedText
DocTgt.Close True
End If
End With
Set DocTgt = Nothing: Set DocSrc = Nothing
Application.ScreenUpdating = True
End Sub

Trying to use VBA to Automate Document Splitting in Word

I am trying to VBA my way into automating a process that my team and myself currently do manually-- taking a Word document and splitting it into multiple documents based on H1 sections (by which I mean, if a doc has 6 H1s, then we wind up with 6 documents).
I have found some code that works well enough, but there are a couple pieces that I can't quite puzzle out.
Getting the footers from my original document to show up in the subdocuments, and
adding a sequential number at the start of each file name.
The former requirement is pretty simple-- my original doc has a footer on it, and I'd like the documents that the code spits out to have the same footer. Right now, the resulting files have blank footers. The latter requirement is that I ultimately would like the new files to have file names with the format "XX - [HeadingText].docx". The code I'm using gets me the heading text just fine, but I can't seem to plug in the sequential numbering.
Here's the code I'm using; any help would be appreciated!
Sub SeparateHeadings()
'
' SeparateHeadings Macro
'
'
Application.ScreenUpdating = False
Dim StrTmplt As String, StrPath As String, StrFlNm As String, Rng As Range, Doc As Document, i As Long
Dim iTemp As Integer
With ActiveDocument
StrTmplt = .AttachedTemplate.FullName
StrPath = .Path & "\"
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Style = "Heading 1"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range.Duplicate
With Rng
StrFlNm = Replace(.Text, vbCr, "")
For i = 1 To 255
Select Case i
Case 1 To 31, 33, 34, 37, 42, 44, 46, 47, 58 - 63, 91 - 93, 96, 124, 147, 148
StrFlNm = Replace(StrFlNm, Chr(i), "")
End Select
Next
iTemp = iTemp + 1
Do
If .Paragraphs.Last.Range.End = ActiveDocument.Range.End Then Exit Do
Select Case .Paragraphs.Last.Next.Style
Case "Heading 1"
Exit Do
Case Else
.MoveEnd wdParagraph, 1
End Select
Loop
End With
Set Doc = Documents.Add(Template:=StrTmplt, Visible:=False)
With Doc
.Range.FormattedText = Rng.FormattedText
.SaveAs2 FileName:=StrPath & StrFlNm, Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close False
End With
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End With
Set Doc = Nothing: Set Rng = Nothing
Application.ScreenUpdating = True
End Sub
Try:
Sub SplitDocByHeading1()
Application.ScreenUpdating = False
Dim StrTmplt As String, StrPath As String, StrFlNm As String
Dim Rng As Range, i As Long, j As Long, Doc As Document
Const StrNoChr As String = """*./\:?|"
With ActiveDocument
StrTmplt = .FullName
StrPath = .Path & "\"
'Convert auto numbering to static numbering
.ConvertNumbersToText (wdNumberAllNumbers)
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Style = wdStyleHeading1
.Format = True
.Forward = True
.Wrap = wdFindStop
.Execute
End With
Do While .Find.Found
Set Rng = .Duplicate: i = i + 1
StrFlNm = Split(Rng.Paragraphs(1).Range.Text, vbCr)(0)
For j = 1 To Len(StrNoChr)
StrFlNm = Replace(StrFlNm, Mid(StrNoChr, j, 1), "_")
Next
StrFlNm = Format(i, "00") & "_" & StrFlNm & ".docx"
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set Doc = Documents.Add(Template:=StrTmplt, Visible:=False)
With Doc
.Range.FormattedText = Rng.FormattedText
.SaveAs2 FileName:=StrPath & StrFlNm, Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close False
End With
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End With
Set Doc = Nothing: Set Rng = Nothing
Application.ScreenUpdating = True
End Sub

How can I convert a word to a hyperlink linking to a Bookmark in the same document?

I really have problems with this one. Imagine I have the word „stackoverflow“. At the end of the document there is a glossary. Now I need a macro that searches for all occurences of stackoverflow and replaces them with a hyperlink to the bookmark in the table. A reader still sees „stackoverflow“ but can click on it to jump to the Glossary. I can insert online links in „address“ field and think I need the subaddress field but do not know what to put there.. Thank you in advance!
Sub Convert_String()
Dim Word
Dim R As Range
Dim Tabellenanzahl
Dim T As Table
Dim Link As Hyperlink
Set R = ActiveDocument.Range
Tabellenanzahl = ActiveDocument.Tables.Count
Set T = ActiveDocument.Tables(Tabellenanzahl)
ActiveDocument.Bookmarks.Add "Anker", T.Range
For Z = 2 To T.Rows.Count
Set Wort = T.Cell(Z, 1)
With R.Find
.ClearFormatting
.Text = Word
.Forward = True
.Wrap = wdFindStop
End With
Do While R.Find.Execute
R.Hyperlinks.Add Anchor:=Selection, SubAddress:="Anker", TextToDisplay:="GoToGlossaryTest"
Loop
Next
End Sub
Try:
Sub GlossaryLinker()
Application.ScreenUpdating = False
Dim Tbl As Table, Rng As Range, HLnk As Hyperlink
Dim strFnd As String, BkMkNm As String, r As Long
With ActiveDocument
Set Tbl = .Tables(.Tables.Count)
For r = 2 To Tbl.Rows.Count
With Tbl.Cell(r, 1)
Set Rng = .Range
With Rng
.End = .End - 1
strFnd = Trim(Split(.Text, vbCr)(0))
BkMkNm = Replace(strFnd, " ", "_")
.Bookmarks.Add BkMkNm, .Duplicate
End With
End With
Set Rng = .Range(.Range.Start, Tbl.Range.Start)
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = False
.Text = strFnd
.Wrap = wdFindStop
.MatchWholeWord = True
.MatchWildcards = False
.MatchCase = True
.Execute
End With
Do While .Find.Found
If .InRange(Rng) = False Then Exit Do
Set HLnk = .Hyperlinks.Add(.Duplicate, , BkMkNm, , .Text)
.End = HLnk.Range.End
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Next
End With
Application.ScreenUpdating = True
End Sub

How to split a Word document (docx or rtf) using a heading1 style as the split

I have a large file I have split into many separate rtf files with this slightly modified code I got online. The problem was I didn't want to include the Heading 1 text in the output file. However the Heading 1 data is used to create the filename of each output document.
This is the format of the file I am splitting to new files.
1.1.1 This would be marked Heading1 style
some text in here some text in here some text in here some text in here
1.1.2 This would be marked Heading1 style
some text in here some text in here some text in here some text in here
1.1.3 This would be marked Heading1 style
some text in here some text in here some text in here some text in here
=============================================================================== So what it outputs are files named 1.1.1.rtf, 1.1.2.rtf etc and would just contain the body text, but no heading.
repeats to end
Any guidance will be appreciated.
Sub aSplitOnHeadings()
'
' SplitOnHeadings Macro
'
'
Application.ScreenUpdating = False
Dim StrTmplt As String, StrPath As String, StrFlNm As String, Rng As Range, Doc As Document, i As Long, extension As String
extension = ".rtf" ' Jon added so we can have 1.1.1 for the references
With ActiveDocument
StrTmplt = .AttachedTemplate.FullName
StrPath = .Path & "\"
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Style = "Heading 1"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range.Duplicate
With Rng
StrFlNm = Replace(.Text, vbCr, "")
For i = 1 To 255 'I took out the chr 46 the full stop because it is legal 44 comma
Select Case i
Case 1 To 31, 33, 34, 37, 42, 47, 58 - 63, 91 - 93, 96, 124, 147, 148
StrFlNm = Replace(StrFlNm, Chr(i), "")
End Select
Next
Do
If .Paragraphs.Last.Range.End = ActiveDocument.Range.End Then Exit Do
Select Case .Paragraphs.Last.Next.Style
Case "Heading 1"
Selection.EndKey Unit:=wdLine
Exit Do
Case Else
.MoveEnd wdParagraph, 1
End Select
Loop
End With
Set Doc = Documents.Add(Template:=StrTmplt, Visible:=False)
With Doc
.Range.FormattedText = Rng.FormattedText
.SaveAs2 FileName:=StrPath & StrFlNm & extension, Fileformat:=wdFormatRTF, AddToRecentFiles:=False
.Close False
End With
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End With
Set Doc = Nothing: Set Rng = Nothing
Application.ScreenUpdating = True
'.SaveAs2 FileName:=StrPath & StrFlNm, FileFormat:=wdFormatRTF, AddToRecentFiles:=False
'.SaveAs2 FileName:=StrPath & StrFlNm, Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
End Sub
These two sets macro will work. Each one splits a document on Heading1 style into separate documents with the document named as the Heading1 it was split at, and the Heading1 is not included in the new document. That is just perfect.
Here are the two sets of macro two for output in .rtf and two for docx Also in these macro I removed the . from being an illegal character as I did need the output to be as per the Heading1 exactly. Thanks macropod for taking the time to sort this. I will try to learn more about macros.
Jon.
Sub SplitDocOnHeading1ToRtfWithHeadingInOutput()
'Splits the document on Heading1 style, into new documents, Heading1 is included in the data.
Application.ScreenUpdating = False
Dim Rng As Range, DocSrc As Document, DocTgt As Document
Dim i As Long, StrTxt As String: Const StrNoChr As String = """*/\:?|"
Set DocSrc = ActiveDocument
With DocSrc.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Forward = True
.Text = ""
.Style = wdStyleHeading1
.Replacement.Text = ""
.Wrap = wdFindStop
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set DocTgt = Documents.Add(DocSrc.AttachedTemplate.FullName)
With DocTgt
Application.ScreenUpdating = False
.Range.FormattedText = Rng.FormattedText
StrTxt = Split(.Paragraphs.First.Range.Text, vbCr)(0)
' Strip out illegal characters
For i = 1 To Len(StrNoChr)
StrTxt = Replace(StrTxt, Mid(StrNoChr, i, 1), "_")
Next
'.Paragraphs.First.Range.Delete 'un comment this line if you don't want to retain headings in the output file
.SaveAs2 FileName:=DocSrc.Path & "\" & StrTxt & ".rtf", Fileformat:=wdFormatRTF, AddToRecentFiles:=False
.Close False
End With
.Start = Rng.End
.Find.Execute
Loop
End With
Set Rng = Nothing: Set DocSrc = Nothing: Set DocTgt = Nothing
Application.ScreenUpdating = True
End Sub
Sub SplitDocOnHeading1ToRtfNoHeadingInOutput()
'Splits the document on Heading1 style, into new documents, Heading1 is NOT included in the data
Application.ScreenUpdating = False
Dim Rng As Range, DocSrc As Document, DocTgt As Document
Dim i As Long, StrTxt As String: Const StrNoChr As String = """*/\:?|"
Set DocSrc = ActiveDocument
With DocSrc.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Forward = True
.Text = ""
.Style = wdStyleHeading1
.Replacement.Text = ""
.Wrap = wdFindStop
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set DocTgt = Documents.Add(DocSrc.AttachedTemplate.FullName)
With DocTgt
Application.ScreenUpdating = False
.Range.FormattedText = Rng.FormattedText
StrTxt = Split(.Paragraphs.First.Range.Text, vbCr)(0)
' Strip out illegal characters
For i = 1 To Len(StrNoChr)
StrTxt = Replace(StrTxt, Mid(StrNoChr, i, 1), "_")
Next
.Paragraphs.First.Range.Delete 'comment out this line if you want to retain headings in the output file
.SaveAs2 FileName:=DocSrc.Path & "\" & StrTxt & ".rtf", Fileformat:=wdFormatRTF, AddToRecentFiles:=False
.Close False
End With
.Start = Rng.End
.Find.Execute
Loop
End With
Set Rng = Nothing: Set DocSrc = Nothing: Set DocTgt = Nothing
Application.ScreenUpdating = True
End Sub
Sub SplitDocOnHeading1ToDocxWithHeadingInOutput()
'Splits the document on Heading1 style, into new documents, Heading1 is included in the data.
Application.ScreenUpdating = False
Dim Rng As Range, DocSrc As Document, DocTgt As Document
Dim i As Long, StrTxt As String: Const StrNoChr As String = """*/\:?|"
Set DocSrc = ActiveDocument
With DocSrc.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Forward = True
.Text = ""
.Style = wdStyleHeading1
.Replacement.Text = ""
.Wrap = wdFindStop
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set DocTgt = Documents.Add(DocSrc.AttachedTemplate.FullName)
With DocTgt
Application.ScreenUpdating = False
.Range.FormattedText = Rng.FormattedText
StrTxt = Split(.Paragraphs.First.Range.Text, vbCr)(0)
' Strip out illegal characters
For i = 1 To Len(StrNoChr)
StrTxt = Replace(StrTxt, Mid(StrNoChr, i, 1), "_")
Next
'.Paragraphs.First.Range.Delete 'un comment this line if you don't want to retain headings in the output file
.SaveAs2 FileName:=DocSrc.Path & "\" & StrTxt & ".docx", Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close False
End With
.Start = Rng.End
.Find.Execute
Loop
End With
Set Rng = Nothing: Set DocSrc = Nothing: Set DocTgt = Nothing
Application.ScreenUpdating = True
End Sub
Sub SplitDocOnHeading1ToDocxNoHeadingInOutput()
'Splits the document on Heading1 style, into new documents, Heading1 is NOT included in the data
Application.ScreenUpdating = False
Dim Rng As Range, DocSrc As Document, DocTgt As Document
Dim i As Long, StrTxt As String: Const StrNoChr As String = """*/\:?|"
Set DocSrc = ActiveDocument
With DocSrc.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Forward = True
.Text = ""
.Style = wdStyleHeading1
.Replacement.Text = ""
.Wrap = wdFindStop
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set DocTgt = Documents.Add(DocSrc.AttachedTemplate.FullName)
With DocTgt
Application.ScreenUpdating = False
.Range.FormattedText = Rng.FormattedText
StrTxt = Split(.Paragraphs.First.Range.Text, vbCr)(0)
' Strip out illegal characters
For i = 1 To Len(StrNoChr)
StrTxt = Replace(StrTxt, Mid(StrNoChr, i, 1), "_")
Next
.Paragraphs.First.Range.Delete 'comment out this line if you want to retain headings in the output file
.SaveAs2 FileName:=DocSrc.Path & "\" & StrTxt & ".docx", Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close False
End With
.Start = Rng.End
.Find.Execute
Loop
End With
Set Rng = Nothing: Set DocSrc = Nothing: Set DocTgt = Nothing
Application.ScreenUpdating = True
End Sub
Try something based on:
Sub SplitDoc()
Application.ScreenUpdating = False
Dim Rng As Range, DocSrc As Document, DocTgt As Document
Dim i As Long, StrTxt As String: Const StrNoChr As String = """*./\:?|"
Set DocSrc = ActiveDocument
With DocSrc.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Forward = True
.Text = ""
.Style = wdStyleHeading1
.Replacement.Text = ""
.Wrap = wdFindStop
.Execute
End With
Do While .Find.Found
Set Rng = .Paragraphs(1).Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
Set DocTgt = Documents.Add(DocSrc.AttachedTemplate.FullName)
With DocTgt
.Range.FormattedText = Rng.FormattedText
StrTxt = Split(.Paragraphs.First.Range.Text, vbCr)(0)
' Strip out illegal characters
For i = 1 To Len(StrNoChr)
StrTxt = Replace(StrTxt, Mid(StrNoChr, i, 1), "_")
Next
.Paragraphs.First.Range.Delete
.SaveAs2 FileName:=DocSrc.Path & "\" & StrTxt & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
.Close False
End With
.Start = Rng.End
.Find.Execute
Loop
End With
Set Rng = Nothing: Set DocSrc = Nothing: Set DocTgt = Nothing
Application.ScreenUpdating = True
End Sub