Opening an already mail merged docx file from Ms access using vba [duplicate] - vba

I have a word document that uses mail merge feature and gets its information from the access db. When I use this code it does not open the word document with the current information. It opens the word document with the last saved information.
If I open the word document on its own, from the task bar, it asks if I want to run the SQL and I click yes and everything operates normally. I want to click a button from within access to accomplish this same task to open the contract.
Here is the code I used:
Private Sub Command205_Click()
Dim LWordDoc As String
Dim oApp As Object
'Path to the word document
LWordDoc = "C:\Users\.....k Up\01- Proposal\contract.docx"
If Dir(LWordDoc) = "" Then
MsgBox "Document not found."
Else
'Create an instance of MS Word
Set oApp = CreateObject(Class:="Word.Application")
oApp.Visible = True
'Open the Document
oApp.Documents.Open FileName:=LWordDoc
End If
End Sub
***I should add that I am not a coder and know nothing about VBA, I copied this from this website so any help you can offer would be greatly appreciated. If you can provide me with coding or enough guidance to get me on the way would be great. Thank you

This code will run in Access to open a Mail Merge document and update content and save.
Using the link I originally posted (http://www.minnesotaithub.com/2015/11/automatic-mail-merge-with-vba-and-access/), I made a couple of modifications and was able to get that code to work.
I needed to add: ReadOnly:=True, _ to prevent a sharing violation
and I changed the Table Name of the source data.
NOTE!! You will need to change sode marked with'###' as follows:
###-1 Change to specify the full path of your TEMPLATE!!!
###-2 Change the SQLSTATEMENT to specify your recordsource!!!
Paste this code into your form, make sure you have a Command Button Click Event that executes (Either rename 'Command205' in this code, or change your control name).
Option Compare Database
Option Explicit
Private Sub Command205_Click()
Dim strWordDoc As String
'Path to the word document of the Mail Merge
'###-1 CHANGE THE FOLLOWING LINE TO POINT TO YOUR DOCUMENT!!
strWordDoc = "C:\Users\.....k Up\01- Proposal\contract.docx"
' Call the code to merge the latest info
startMerge strWordDoc
End Sub
'----------------------------------------------------
' Auto Mail Merge With VBA and Access (Early Binding)
'----------------------------------------------------
' NOTE: To use this code, you must reference
' The Microsoft Word 14.0 (or current version)
' Object Library by clicking menu Tools > References
' Check the box for:
' Microsoft Word 14.0 Object Library in Word 2010
' Microsoft Word 15.0 Object Library in Word 2013
' Click OK
'----------------------------------------------------
Function startMerge(strDocPath As String)
Dim oWord As Word.Application
Dim oWdoc As Word.Document
Dim wdInputName As String
Dim wdOutputName As String
Dim outFileName As String
' Set Template Path
wdInputName = strDocPath ' was CurrentProject.Path & "\mail_merge.docx"
' Create unique save filename with minutes and seconds to prevent overwrite
outFileName = "MailMergeFile_" & Format(Now(), "yyyymmddmms")
' Output File Path w/outFileName
wdOutputName = CurrentProject.Path & "\" & outFileName
Set oWord = New Word.Application
Set oWdoc = oWord.Documents.Open(wdInputName)
' Start mail merge
'###-2 CHANGE THE SQLSTATEMENT AS NEEDED
With oWdoc.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:=CurrentProject.FullName, _
ReadOnly:=True, _
AddToRecentFiles:=False, _
LinkToSource:=True, _
Connection:="QUERY mailmerge", _
SQLStatement:="SELECT * FROM [tblEmployee]" ' Change the table name or your query
.Destination = wdSendToNewDocument
.Execute Pause:=False
End With
' Hide Word During Merge
oWord.Visible = False
' Save file as PDF
' Uncomment the line below and comment out
' the line below "Save file as Word Document"
'------------------------------------------------
'oWord.ActiveDocument.SaveAs2 wdOutputName & ".pdf", 17
' Save file as Word Document
' ###-3 IF YOU DON'T WANT TO SAVE AS A NEW NAME, COMMENT OUT NEXT LINE
oWord.ActiveDocument.SaveAs2 wdOutputName & ".docx", 16
' SHOW THE DOCUMENT
oWord.Visible = True
' Close the template file
If oWord.Documents(1).FullName = strDocPath Then
oWord.Documents(1).Close savechanges:=False
ElseIf oWord.Documents(2).FullName = strDocPath Then
oWord.Documents(2).Close savechanges:=False
Else
MsgBox "Well, this should never happen! Only expected two documents to be open"
End If
' Quit Word to Save Memory
'oWord.Quit savechanges:=False
' Clean up memory
'------------------------------------------------
Set oWord = Nothing
Set oWdoc = Nothing
End Function

Related

How to search and replace across multiple word documents in the same folder?

I've tried to use the below code which I found on this conversation How To Search And Replace Across Multiple Files In Word? supplied by Charles Kenyon. However, it doesn't seem to work for me. I've enabled macros on my word and added the below code as a new module in Macros. When I go to replace all, it'll replace the text as per normal, but after doing this, when I open up the other macros enabled word doc, I find that the same text is still in these docs, without being replaced. Am I doing something wrong? Namely, I also wish to add a wildcard entry into my replace all, will the below code work or can someone suggest a better alternative? I have tested the below code with and without wildcard entries to no avail. I've also tried the code on this page in my macros but it also didn't work How to find and replace a text in multiple Word documents using VBAThanks for any help!
Option Explicit
Public Sub BatchReplaceAll()
Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
PathToUse = "C:\Test\"
'Error handler to handle error generated whenever
'the FindReplace dialog is closed
On Error Resume Next
'Close all open documents before beginning
Documents.Close SaveChanges:=wdPromptToSaveChanges
'Boolean expression to test whether first loop
'This is used so that the FindReplace dialog will
'only be displayed for the first document
FirstLoop = True
'Set the directory and type of file to batch process
myFile = Dir$(PathToUse & "*.doc")
While myFile <> ""
'Open document
Set myDoc = Documents.Open(PathToUse & myFile)
If FirstLoop Then
'Display dialog on first loop only
Dialogs(wdDialogEditReplace).Show
FirstLoop = False
Response = MsgBox("Do you want to process " & _
"the rest of the files in this folder", vbYesNo)
If Response = vbNo Then Exit Sub
Else
'On subsequent loops (files), a ReplaceAll is
'executed with the original settings and without
'displaying the dialog box again
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
End If
'Close the modified document after saving changes
myDoc.Close SaveChanges:=wdSaveChanges
'Next file in folder
myFile = Dir$()
Wend
End Sub

How to open a document with VBA on a Mac?

I'm trying to write a Macro to batch process a bunch of Word docs. I need to set the page size to "Legal" for more than 200 files. The code I've written is pretty simple and seems like it should work, but I can't get the Documents.Open command to execute successfully. Every time I get this result:
Run-time error '5174': This file could not be found.
(et cetera) -- even when I hard-code the filename. The file definitely does exist. Here's what I've got so far:
Public Sub MassFormatLegal()
Dim vDirPath As String
Dim vFile As String
Dim vFileName As String
Dim oDoc As Document
vDirPath = "MacMiniHD:Users:atc:Documents:TEST:"
vFile = Dir(vDirPath)
Do While vFile <> ""
vFileName = vDirPath & vFile
'* display the filename to verify that it's correct
MsgBox "vFileName: " + vFileName
'* open file
Set oDoc = Documents.Open("MacMiniHD:Users:atc:Documents:TEST:AAFILE.doc")
'* I also tried the following, all resulting in the same error
'*Set oDoc = Documents.Open(vFileName)
'*Set oDoc = Documents.Open(fileName:=vFileName)
'*Set oDoc = Application.Documents.Open(fileName:=vDirPath & vFile)
'* change paper size
oDoc.PageSetup.PaperSize = wdPaperLegal
'* save and close the document
oDoc.Close wdSaveChanges
'* get next file
vFile = Dir
Loop
MsgBox "Finished"
End Sub
Any suggestions? I've tried a lot of different approaches and am realizing that there are serious limitations of VBScript for Mac, but surely this kind of basic file handling is possible?!?

Word bookmarks template using Access data

I have a Word template with bookmarks. These bookmarks pull data from an Access database application via VBA code.
On Error GoTo ErrHandler
Me.Recalc
If Me!txtCount = 0 Then
MsgBox "Please select a record to print.", vbOKOnly, "Error"
Else
Dim oWord As Object 'Word.Application
Dim doc As Object 'Word.Document
Set oWord = CreateObject("Word.Application")
Set doc = oWord.Documents.Open("C:\Request_Template.doc")
oWord.Visible = True
Dim oAccess As Object
Dim dbs As Database
Dim rst As Recordset
Dim strCriteria As String
With oWord.ActiveDocument
If .Bookmarks.Exists("DatePage1") = True Then
.Bookmarks("DatePage1").Select
If Not IsNull([Forms]![frmForRequest_Preview]!Date) Then
oWord.selection.Text = (CStr(Format([Forms]![frmForRequest_Preview]!Date, "mmm d, yyyy")))
Else
oWord.selection.Text = ""
End If
End With
End If
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
The question is how to open a copy of the template to allow the user to click on "Save" after reviewing the document? For now the original template is used and the user has to perform "Save As". That is not convenient.
"Template" in Word is a specific file type (.dot, .dotx or .dotm). As it stands, you don't have a Word "template", just a standard Word document (.doc).
Open this .doc in Word and save it as a "Document Template (.dot).
Now, change the line Documents.Open to Documents.Add, referencing the new .dot and changing the parameters to match those of the Add method.
This will automatically open a COPY of the template file, so there is never any danger of the user or your code overwriting the template.
Note, however, that "Save As" is still required since this is a new document, but it will come up automatically - the user won't have to think to use Save As. If you don't want the user to see Save As at all your code needs to perform Document.SaveAs and you need to know the file path and location to which it should be saved.

copy formatted text into access using vba

I need to save formatted text from Word in an Access Database.
So far I've managed to figure out how to store formatted text in an Access Field (Create a Memo Field in a Table and set the Text Format as Rich Text). Searching SO I have not yet come across a solution as to how to transport said text from word into Access.
I know that it is possible, because you can do it by simply copying and pasting the information if you are doing it manually.
My question, how can I copy formatted text from word into a field in a table using VBA?
Experimentally I created the following to test this. So far without success...
Sub GetComments()
'Imports Analyst Comments from Excel files als OLE Objects.
'---------------------------------
'Access Variables
Dim dbsFundDB As DAO.Database
Dim rsComments As DAO.Recordset
Set dbsFundDB = CurrentDb
Set rsComments = dbsFundDB.OpenRecordset("tblFunds")
'Word Variables
Dim doc As Word.Application
Dim dcmt As Word.Document
Dim sectn As Word.Section
Dim obCommentText As Object
Dim sAnalystText As String
'Open New Word File
Set doc = New Word.Application
doc.Visible = True
Set dcmt = doc.Documents.Open(sPathTemplate)
Set sectn = dcmt.Sections(1)
sectn.Range.Select
Selection.InsertFile FileName:="myfile.rtf", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
sAnalystText = sectn.Range.Tables(1).cell(1, 1).Range.FormattedText
rsComments.AddNew
rsComments![Long Comment Exec] = sAnalystText
rsComments.Update
sectn.Range.Select
dcmt.Close savechanges:=False
doc.Quit
End Sub
UPDATE
I tried implementing the answer from Matt Hall. While the text is indeed copied to the database, it does not yet keep the formatting:
Here is my implementation as a simple test:
Option Explicit
Public Const sPathTemplate As String = "W:\L\BDTP\Products\FundResearchTool\Advisory.docx"
Option Compare Database
Sub GetComments()
'Imports Comments from word and save in DB
'Test soubroutine
'---------------------------------
'Word Variables
Dim obCommentText As Variant
Dim strSQL As String
obCommentText = GetWordContent(sPathTemplate)
strSQL = "insert into [tblText]([TestField]) values('" & obCommentText & "')"
DoCmd.RunSQL strSQL
MsgBox "Import Successful", vbInformation Or vbOKOnly
End Sub
Private Function GetWordContent(strFile As String) As Variant
' This function takes the path obtained to the MS-Word Document selected in
' the FileToOpen function and then uses that to open that MS-Word Document
' and retrieve its text contents
Dim objDoc As Word.Document
Set objDoc = GetObject(strFile)
GetWordContent = CVar(objDoc.Sections(1).Range.Text)
objDoc.Close
End Function
Here's a method that heavily references this.
Before you start make sure you have these (or your Access version's equivalent) references ticked in VBA editor > Tools > References:
Microsoft Word 15.0 Object Library
Microsoft Office 15.0 Object Library
Assuming you've set up a form with a command button to trigger this MS-Word import, put the following function and subroutine somewhere in that form's VBA module:
1) File Picker Function:
This will allow you to select the MS-Word Document you want to using the old familiar file dialogue window you see throughout Windows. Ultimately, all it does is save the file path and name of the file you've picked for use in in the subroutine described in (2)...
Private Function FileToOpen() As String
' This function will essentially allow you to browse to MS-Word document
' and then store the path of that file for use in the GetWordContent function
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Select Word document to import"
.Filters.Clear
.Filters.Add "Word files", "*.doc?"
If _
.Show = True _
Then
For Each varFile In .SelectedItems
FileToOpen = varFile
Next
Else
FileToOpen = ""
End If
End With
End Function
2) Get Formatted Text Contents of MS-Word Document Subroutine:
This subroutine will use the file path and name of the MS-Word Document selected in the File Picker function (above) to open the MS-Word document, select all the text, copy it to the clipboard, paste it to a text box on an open form in Access and then close MS-Word...
Private Sub GetWordContent(strFile As String)
' This function takes the path obtained to the MS-Word Document selected in
' the FileToOpen function and then uses that to open that MS-Word Document
' and retrieve its text contents and paste them in to WordDocData textbox on
' the currently open form in Access
' Create an MS-Word Object:
Dim objDoc As Object
Set objDoc = CreateObject("Word.Application")
' Open the file selected in FileToOpen() and copy the contents to clipboard:
With objDoc
.Documents.Open strFile
.Visible = True
.Activate
.Selection.WholeStory
.Selection.Copy
End With
' Set the focus to the WordDocData textbox on the Access Form and paste clipboard:
Me.WordDocData.SetFocus
DoCmd.RunCommand acCmdPaste
Me.WordDocDataSrc = strFile
' Save record on the form:
If _
Me.Dirty _
Then
Me.Dirty = False
End If
' A bit hacky this bit. When you close MS-Word after copying a lot of data,
' you might get a message asking you if you if you want to keep the last item
' you copied. This essentially overwrites the clipboard that currently has
' the whole document stored, to just the first 5 characters, which should allow
' MS-Word to be closed here without a pop-up message to deal with:
With objDoc
.Selection.HomeKey Unit:=wdLine
.Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
.Selection.Copy
.Documents.Close
.Quit
End With
Set objDoc = Nothing
End Sub
Your Command Button's On-click Event:
This subroutine should be run from your command button's on-click event. It essentially calls FileToOpen function and the GetWordContent subroutine in order for the user to select a MS-Word Document and then let the VBA copy and paste the formatted text from the MS-Word Document in to a rich text memo textbox on the open form in Access.
Note that this subroutine makes some assumptions, and refers to names of controls/tables/fields and whatnot that you might not have already setup. These assumptions are:
Your form's command button is called cmdGetWordData
Your Access database has a table called tblWordDump
Your form is bound to the table tblWordDump
tblWordDump has 2 memo text fields called WordDocDataSrc and WordDocData to store the imported file path/name and text contents respectively and both are added to your form
Private Sub cmdGetWordData_Click()
' This subroutine runs on your command button; it will call both the FileToOpen function and GetWordContent subroutine
' to retrieve the text contents of your chosen MS-Word Document.
' It will then store both the path the text contents of of your chosen MS-Word Document in 2 fields in a table in Access.
' NOTE: this code assumes that your Access database has:
' - a table called tblWordDump
' - a memo text field in this table called WordDocDataSrc to store the path of MS-Word file imported
' - a memo text field in this table called WordDocData with the TextFormat property set to "Rich Text",
' which will store the text and text formating of the MS-Word file imported
Dim strFile As String
Dim strWordContent As Variant
' Select file via File Dialogue
strFile = FileToOpen
' Conditionals when a file was or wasn't selected
If _
Len(strFile) > 0 _
Then
DoCmd.GoToRecord , , acNewRec
GetWordContent strFile
MsgBox "Import Successful", vbInformation Or vbOKOnly
Else
MsgBox "No File Selected", vbExclamation Or vbOKOnly
End If
End Sub
Here's an example Access file of this for you to poke about in.

How to split a mail merge and save files with a merge field as the name

I have a bunch of mail merge templates setup, when I merge the documents I want to split the results into separate files each one with a name based on the merge field “FileNumber”.
The code I have currently is:
Sub splitter()
' Based on a macro by Doug Robbins to save each letter created by a mailmerge as a separate file.
' With help from http://www.productivitytalk.com/forums/topic/3927-visual-basic-question-for-merge-fields/
Dim i As Integer
Dim Source As Document
Dim Target As Document
Dim Letter As Range
Dim oField As Field
Dim FileNum As String
Set Source = ActiveDocument
For i = 1 To Source.Sections.Count
Set Letter = Source.Sections(i).Range
Letter.End = Letter.End - 1
For Each oField In Letter.Fields
If oField.Type = wdFieldMergeField Then
If InStr(oField.Code.Text, "FileNumber") > 0 Then
'get the result and store it the FileNum variable
FileNum = oField.Result
End If
End If
Next oField
Set Target = Documents.Add
Target.Range = Letter
Target.SaveAs FileName:="C:\Temp\Letter" & FileNum
Target.Close
Next i
End Sub
The problem is if I “Merge to new document” then the “FileNumber” field no longer exists so it can’t pick that up but if I just go to “Preview Results” and run the macro it only saves the currently previewed record and not the rest of the letters.
I’m assuming I need to change the code to something like
For i = 1 To Source.MergedRecord.Count
Set Letter = Source.MergedRecord(i).Range
but I can't work out the correct syntax.
I am aware of http://www.gmayor.com/individual_merge_letters.htm but I don't want the dialog boxes I just want a one click button.
In the Mail merge template document, paste the following macro code in "ThisDocument" module:
Dim WithEvents wdapp As Application
Dim bCustomProcessing As Boolean
Private Sub Document_Open()
Set wdapp = Application
bCustomProcessing = False
ThisDocument.MailMerge.DataSource.ActiveRecord = 1
ThisDocument.MailMerge.ShowWizard 1
With ActiveDocument.MailMerge
If .MainDocumentType = wdFormLetters Then
.ShowSendToCustom = "Custom Letter Processing"
End If
End With
End Sub
Private Sub wdapp_MailMergeWizardSendToCustom(ByVal Doc As Document)
bCustomProcessing = True
Doc.MailMerge.Destination = wdSendToNewDocument
With Doc.MailMerge
For rec = 1 To .DataSource.RecordCount
.DataSource.ActiveRecord = rec
.DataSource.FirstRecord = rec
.DataSource.LastRecord = rec
.Execute
Next
End With
MsgBox "Merge Finished"
End Sub
Private Sub wdapp_MailMergeAfterMerge(ByVal Doc As Document, ByVal DocResult As Document)
If bCustomProcessing = True Then
With Doc.MailMerge.DataSource.DataFields
sFirmFileName = .Item(1).Value ' First Column of the data - CHANGE
End With
DocResult.SaveAs "c:\path\" & sFirmFileName & ".docx", wdFormatXMLDocument
' Path and File Name to save. can use other formats like wdFormatPDF too
DocResult.Close False
End If
End Sub
Remember to update the column number to use for file names, and the path to save the generated files.
After writing this code, save and close the merge template doc. Re-open the file and this time you will be prompted with the Merge wizard. Proceed as required for the Letter, and at the last step, select "Custom Letter Processing" option instead of finishing merge. This will save the separate merged docs in specified folder.
Please remember that this code can be heavy on the processor.
There is a simple solution not involving splitting the resulting document:
Prepare the merge and staying in the template document.Record a macro as you merge one record, then save and close the resulting file, eventuallye advance to the next record.
See the generated macro below. I have added very little code just to extract the filename from a field in the datasource (which is accessible in the template document).
Assign the macro to a shortcut key or implement a loop in VBA. Observe that the fieldnames are casesensitive.
Regards,
Søren
Sub flet1()
'
' flet1 Makro
' 1) Merges active record and saves the resulting document named by the datafield FileName"
' 2) Closes the resulting document, and (assuming that we return to the template)
' 3) advances to the next record in the datasource
'
'Søren Francis 6/7-2013
Dim DokName As String 'ADDED CODE
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
.LastRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
' Remember the wanted documentname
DokName = .DataFields("FileName").Value ' ADDED CODE
End With
' Merge the active record
.Execute Pause:=False
End With
' Save then resulting document. NOTICE MODIFIED filename
ActiveDocument.SaveAs2 FileName:="C:\Temp\" + DokName + ".docx", FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False, CompatibilityMode:=14
' Close the resulting document
ActiveWindow.Close
' Now, back in the template document, advance to next record
ActiveDocument.MailMerge.DataSource.ActiveRecord = wdNextRecord
End Sub
Thanks for that roryspop,
I ended up swapping the for loop with
Set Source = ActiveDocument
'The for loop was "To ActiveDocument.MailMerge.DataSource.RecordCount" but for
'some reason RecordCount returned -1 every time, so I set ActiveRecord
'to wdLastRecord and then use that in the for loop.
ActiveDocument.MailMerge.DataSource.ActiveRecord = wdLastRecord
For i = 1 To ActiveDocument.MailMerge.DataSource.ActiveRecord
ActiveDocument.MailMerge.DataSource.ActiveRecord = i
Set Letter = Source.Range
For Each oField In Letter.Fields
The rest of the code is the same, it's not very neat and I'm sure there must be a better way of doing things but it works.
The accepted solution did not work for me. I am using Word 2010. I managed to get a solution working and would like to share it here, so others can benefit from it:
'purpose: save each letter generated after mail merge in a separate file
' with the file name equal to first line of the letter.
'
'1. Before you run a mail merge make sure that in the main document you will
' end your letter with a Section Break (this can be found under
' Page Layout/Breaks/Section Break Next Page)
'2. Furthermore the first line of your letter contains the proposed file name
' and put an enter after it. Make the font of the filename white, to make it
' is invisible to the receiver of the letter. You can also include a folder
' name if you like.
'3. Run the mail merge as usual. A file which contains all the letters is
' generated.
'4. Add this module to the generated mail merge file. Use Alt-F11 to go to the
' visual basic user interface, right click in the left pane on the generated
' file and click on Import File and import this file
'5. save the generate file with all the letters as ‘Word Macro Enabled doc
' (*.docm)’.
'6. close the file.
'7. open the file again, click allow content when a warning about macro's is
' shown.
'8. execute the macro with the name SaveRecsAsFiles
Sub SaveRecsAsFiles()
' Convert all sections to Subdocs
AllSectionsToSubDoc ActiveDocument
'Save each Subdoc as a separate file
SaveAllSubDocs ActiveDocument
End Sub
Private Sub AllSectionsToSubDoc(ByRef doc As Word.Document)
Dim secCounter As Long
Dim NrSecs As Long
NrSecs = doc.Sections.Count
'Start from the end because creating
'Subdocs inserts additional sections
For secCounter = NrSecs - 1 To 1 Step -1
doc.Subdocuments.AddFromRange _
doc.Sections(secCounter).Range
Next secCounter
End Sub
Private Sub SaveAllSubDocs(ByRef doc As Word.Document)
Dim subdoc As Word.Subdocument
Dim newdoc As Word.Document
Dim docCounter As Long
Dim strContent As String, strFileName As String
docCounter = 1
'Must be in MasterView to work with
'Subdocs as separate files
doc.ActiveWindow.View = wdMasterView
For Each subdoc In doc.Subdocuments
Set newdoc = subdoc.Open
'retrieve file name from first line of letter.
strContent = newdoc.Range.Text
strFileName = Mid(strContent, 1, InStr(strContent, Chr(13)) - 1)
'Remove NextPage section breaks
'originating from mailmerge
RemoveAllSectionBreaks newdoc
With newdoc
.SaveAs FileName:=strFileName
.Close
End With
docCounter = docCounter + 1
Next subdoc
End Sub
Private Sub RemoveAllSectionBreaks(doc As Word.Document)
With doc.Range.Find
.ClearFormatting
.Text = "^b"
With .Replacement
.ClearFormatting
.Text = ""
End With
.Execute Replace:=wdReplaceAll
End With
End Sub
Part of the code I copied from here