View Single Post
 
Old 06-30-2022, 07:48 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

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
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote