Quote:
Originally Posted by Guessed
Using the Selection object is not recommended, especially when your code is opening/closing new documents. If your code does the right thing and defines objDoc then it should also start making use of that to ensure the code (and observers) doesn't confuse the new docs with the original doc. Also, you can get big changes in formatting if you are inserting content into a new document with different style definitions. The following changes to the code should deal with each of those problems.
Code:
Sub SaveEachSectionAsADoc()
Dim objDocAdded As Document, objDoc As Document
Dim nSectionNum As Integer, strFolder As String
Dim dlgFile As FileDialog
' Initialization
Set objDoc = ActiveDocument
Set dlgFile = Application.FileDialog(msoFileDialogFolderPicker)
' Pick a location to keep new files.
With dlgFile
If .Show = -1 Then
strFolder = .SelectedItems(1) & "\"
Else
MsgBox "Select a folder first!"
Exit Sub
End If
End With
' Step through each section in current document, copy and paste each to a new one.
For nSectionNum = 1 To objDoc.Sections.Count
Set objDocAdded = Documents.Add(Template:=objDoc.FullName)
objDocAdded.Range.FormattedText = objDoc.Sections(nSectionNum).Range.FormattedText
' Save and close new documents.
objDocAdded.SaveAs FileName:=strFolder & "Section " & nSectionNum & ".docx"
objDocAdded.Close
Next nSectionNum
End Sub
|
Sorry, Andrew, despite hitting refresh on the page I somehow missed your input. You are absolutely right. I encountered some changes in the formatting but thankfully nothing major that necessitates doing over what I had done in the meantime.
EDIT. I tried your code with a slight update and the error for Paste was gone. Imagine I ran Repair on Office 3 times already! Super, many thanks.
Cheers,
Z.