Word VBA to Save in specific Directory with Merge Field as File Name and Prompt - vba

Background:
I have created an Excel template to mail merge the fields into a Word document and generate 5 different letters which would go out to ONE customer.
Mission:
To have the Word VBA code run an automatic mail merge and prompt to save (or Autosave) in a specific directory with a file name which is derived from a mail merge field.
ie.
(unique identifier) + Name of First Letter + Date
to be saved in First Letter Folder
(unique identifier) + Name of Second Letter + Date
to be saved in Second Letter Folder
etc..
Issue:
I cannot figure out how to specify the directory or how to insert a mail merge field as a part of the file name.
The following is the code that I have
Sub MailMerge()
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
With Dialogs(wdDialogFileSummaryInfo)
.Title = "Letter1Draft" & Format(Now(), "mmddyyyy") & ".doc"
.Execute
End With
' Then this!
With Dialogs(wdDialogFileSaveAs)
.Show
End With
End Sub

The following code picks the directory.
It does not allow you to insert a mail merge field as the file name.
Sub AllSectionsToSubDoc()
Dim x As Long
Dim Sections As Long
Dim Doc As Document
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set Doc = ActiveDocument
Sections = Doc.Sections.Count
For x = Sections - 1 To 1 Step -1
Doc.Sections(x).Range.Copy
Documents.Add
ActiveDocument.Range.Paste
ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
ActiveDocument.Close False
Next x
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Related

Append Word docx files while keeping their format in VBA

I am creating a Word Macro that receives two arguments: a list of docx documents and the name of the new file. The goal is that the Macro inserts one document after the other, preserving their respective format, and saves as a new docx document.
Sub Merger(path As String, args () As Variant)
Dim vArg As Variant
Active Document.Select
Selection.ClearFormatting
For Each vArg In args
ActiveDocument.Content.Words.Last.Select
Selection.InsertFile:= _ vArg _,Range:="", _ConfirmConversions:= False, Link:=False, Attachment:= False )
Selection.InsertBreak Type:=wdPageBreak
Next vArg
ActiveDocument.SaveAs2 File Name=path
ActiveDocument.Close
Application.Quit
Note that I call the Macro from an empty docx file.
The problem is that neither the header nor the format of the orginal files are preserved in the new docx document.
The Word format is not modular. Instead, consider creating a Master Document, then filling it with subdocuments. Here's code to create a master document from a folder full of subdocuments:
Sub AssembleMasterDoc()
Dim SubDocFile$, FolderPath$, Template$
Dim Counter&
Dim oFolder As FileDialog
Dim oBookmark As Bookmark
Dim oTOC As TableOfContents
'Create a dynamic array variable, and then declare its initial size
Dim DirectoryListArray() As String
ReDim DirectoryListArray(1000)
Template$ = ActiveDocument.AttachedTemplate.Path & Application.PathSeparator & ActiveDocument.AttachedTemplate.Name
'Loop through all the files in the directory by using Dir$ function
Set oFolder = Application.FileDialog(msoFileDialogFolderPicker)
With oFolder
.AllowMultiSelect = False
If .Show <> 0 Then
FolderPath$ = .SelectedItems(1)
Else
GoTo EndSub
End If
End With
Application.ScreenUpdating = False
SubDocFile$ = Dir$(FolderPath$ & Application.PathSeparator & "*.*")
Do While SubDocFile$ <> ""
DirectoryListArray(Counter) = SubDocFile$
SubDocFile$ = Dir$
Counter& = Counter& + 1
Loop
'Reset the size of the array without losing its values by using Redim Preserve
ReDim Preserve DirectoryListArray(Counter& - 1)
WordBasic.SortArray DirectoryListArray()
ActiveWindow.ActivePane.View.Type = wdOutlineView
ActiveWindow.View = wdMasterView
Selection.EndKey Unit:=wdStory
For x = 0 To (Counter& - 1)
If IsNumeric(Left(DirectoryListArray(x), 1)) Then
FullName$ = FolderPath$ & Application.PathSeparator & DirectoryListArray(x)
Documents.Open FileName:=FullName$, ConfirmConversions:=False
With Documents(FullName$)
.AttachedTemplate = Template$
For Each oBookmark In Documents(FullName$).Bookmarks
oBookmark.Delete
Next oBookmark
.Close SaveChanges:=True
End With
Selection.Range.Subdocuments.AddFromFile Name:=FullName$, ConfirmConversions:=False
End If
Next x
For Each oTOC In ActiveDocument.TablesOfContents
oTOC.Update
Next oTOC
ActiveWindow.ActivePane.View.Type = wdPrintView
Application.ScreenUpdating = True
EndSub:
End Sub
This code is from a previous project, so you may not need all of it, like the update of multiple TOCs.
Don't attempt to maintain and edit Master Documents. The format is prone to corruption. Instead, assemble a master document for printing (or other use), then discard it.

VBA Code to change word footer in multiple files based on page number

I have a macro that runs to make a single page doc into a 5 page doc (NCR Duplicates) for all files in a folder.
I am using a set of nested IF fields in my footer, which changes the footer based on page number. The field looks like this
Text here {If{PAGE}="1""Original"{If{PAGE}="2""Copy 1"
{If{PAGE}="3""Copy 2"{If{PAGE}="4""Copy 3"{If{PAGE}="5""Copy 4"}}}}}
Other Text
I am trying to figure out how to add this footer to all the documents in a folder. It doesn't need to use field, if there is a way simply based on page number.
I have bashed my head against the wall, searched like crazy, and now come hat in hand.
The macro to make the duplicate copies is:
Sub Make5CopiesNCR()
vDirectory = BrowseForFolder
vFile = Dir(vDirectory & "\" & "*.*")
Do While vFile <> ""
Documents.Open FileName:=vDirectory & "\" & vFile
MakeCopies
vFile = Dir
Loop
End Sub
End Sub
Private Sub MakeCopies()
Dim i As Integer
Selection.WholeStory
Selection.Copy
For i = 1 To 6
Selection.PasteAndFormat wdFormatOriginalFormatting
Next
With ActiveDocument
.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=6 'Page number
.Bookmarks("\Page").Select
With Selection
.Delete
ActiveDocument.Close SaveChanges:=wdSaveChanges, OriginalFormat:=wdWordDocument
End With
End With
End Sub
The problem with using a mailmerge with your field construction is that it gets converted to the result. Try a field coded as:
{={PAGE}-1 \# "'Copy {={PAGE}-1}';;'Original'"}
Now, if you create the required 5 pages in your mailmerge main document, all the outputs will likewise be in multiples of 5 pages, with the correct page numbering.
Even if you use a mailmerge main document with only a single page, the outputs will have the field coding required to produce the correct numbering for however many more pages you want to add to the outputs.
As for replicating this in your existing files, simply create a document with the required footer content, then use a macro like:
Sub ReplicateFooter()
Application.ScreenUpdating = False
Dim DocSrc As Document, DocTgt As Document, Rng As Range
Dim StrPth As String, StrNm As String, StrSrc As String
Set DocSrc = ActiveDocument
Set Rng = DocSrc.Sections.First.Footers(wdHeaderFooterPrimary).Range
StrPth = DocSrc.Path & "\": StrSrc = DocSrc.FullName
StrNm = Dir(StrPth & "*.doc", vbNormal)
While StrNm <> ""
If StrPth & StrNm <> StrSrc Then
Set DocTgt = Documents.Open(FileName:=StrPth & StrNm, AddToRecentFiles:=False, Visible:=False)
With DocTgt
With .Sections.First.Footers(wdHeaderFooterPrimary).Range
.FormattedText = Rng.FormattedText
.Characters.Last.Text = vbNullString
End With
.Close True
End With
End If
StrNm = Dir()
Wend
Set Rng = Nothing: Set DocTgt = Nothing: Set DocSrc = Nothing
Application.ScreenUpdating = True
End Sub

How can I find & replace text across multiple files inside text boxes?

I would like to change text that repeats in .doc and .docx files.
I have this macro running at the moment:
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:\Files\"
'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 & "*.docx")
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
It does work if replacing simple text.
How can I search and replace inside Text Boxes?
EDIT 1:
I changed this:
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
To this:
With Dialogs(wdDialogEditReplace)
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "ORIGINAL_TEXT"
.Replacement.Text = "MODIFIED_TEXT"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Do While Not (myStoryRange.NextStoryRange Is Nothing)
Set myStoryRange = myStoryRange.NextStoryRange
With myStoryRange.Find
.Text = "ORIGINAL_TEXT"
.Replacement.Text = "MODIFIED_TEXT"
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Loop
Next myStoryRange
End With
The problems with this new code is that sometimes it skips text boxes and it is slow.
In VBA, Word "Text Boxes" are known as a TextFrame Object. This may be able to point you in the right direction:
For Each s In ActiveDocument.Shapes
With s.TextFrame
If .HasText Then MsgBox .TextRange.Text
End With
Next
I will update my answer when I get more information on implementing it into your example.

Export individual documents from mail merge

How would I create individuals files from mail merge rather than the one large file that is output by the mail merge function in Microsoft Office?
I was hoping to be able to save each letter than was created as a name of one of the merge fields, but I haven't been able to find an intuitive way so far...
Recently I've come across the similar situation where I want to save individual files in pdf format rather than saving one large file created by Mail merge function. I've written down this small function to save individual file in pdf format.
Sub SaveAsPDF()
Dim CouncilName As String
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
For SectionCount = 1 To .DataSource.RecordCount
With .DataSource
'FirstRecord and LastRecords defines how many data records needs to be merge in one document.
'createing pdf file for each data record so in this case they are both pointing to ActiveRecord.
.FirstRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
.LastRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
'get the council name from data source
CouncilName = .DataFields("Council").Value
'move to next datasource record.
If .ActiveRecord <> .RecordCount Then
.ActiveRecord = wdNextRecord
End If
End With
'Get path and file name
PDFPathAndName = ActiveDocument.Path & Application.PathSeparator & "FINAL - " & CouncilName & ".pdf"
' Merge the document
.Execute Pause:=False
' Save resulting document.
Set PDFFile = ActiveDocument
PDFFile.ExportAsFixedFormat PDFPathAndName, wdExportFormatPDF
PDFFile.Close 0
Next
End With
End Sub
as of my experience, there is no option to save individual files, instead you can use Macro to spit the files and save it individually with specific name that you want. I have tried the same and succeeded with what want. Hope the below code helps you as well to achieve you goal.
Sub BreakOnSection()
'Used to set criteria for moving through the document by section.
Application.Browser.Target = wdBrowseSection
'A mailmerge document ends with a section break next page.
'Subtracting one from the section count stop error message.
For i = 1 To ((ActiveDocument.Sections.Count) - 1)
'Select and copy the section text to the clipboard
ActiveDocument.Bookmarks("\Section").Range.Copy
'Create a new document to paste text from clipboard.
Documents.Add
'To save your document with the original formatting'
Selection.PasteAndFormat (wdFormatOriginalFormatting)
'Removes the break that is copied at the end of the section, if any.
Selection.MoveUp Unit:=wdLine, Count:=1, Extend:=wdExtend
Selection.Delete Unit:=wdCharacter, Count:=1
ChangeFileOpenDirectory "C:\"
DocNum = DocNum + 1
ActiveDocument.SaveAs FileName:="test_" & DocNum & ".doc"
ActiveDocument.Close
'Move the selection to the next section in the document
Application.Browser.Next
Next i
ActiveDocument.Close savechanges:=wdDoNotSaveChanges
End Sub
Please revert me for any clarifications.
I modified Parth's answer since it didn't work for me.
Sub SaveAsFileName()
Dim FileName As String
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
For SectionCount = 1 To .DataSource.RecordCount
With .DataSource
ActiveDocument.MailMerge.DataSource.ActiveRecord = SectionCount
ActiveDocument.MailMerge.DataSource.FirstRecord = SectionCount
ActiveDocument.MailMerge.DataSource.LastRecord = SectionCount
' replace Filename with the column heading that you want to use - can't have certain symbols in the name
FileName = .DataFields("Filename").Value
End With
'Get path and file name
FullPathAndName = ActiveDocument.Path & Application.PathSeparator & FileName & ".docx"
' Merge the document
.Execute Pause:=False
' Save resulting document.
ActiveDocument.SaveAs (FullPathAndName)
ActiveDocument.Close False
Next
End With
End Sub

Qualify Selection Object in VBA Word

I have a VBA subroutine which performs miscellaneous formatting to Word documents. It relies on the Selection object (Selection.WholeStory) to apply the formatting.
This subroutine is called from VBA Outlook with a Word.Application object.
The problem that arises is: when another instance of Word is open when the macro is called, the Selection Object refers to the Word document already open, not the handler created in my macro.
VBA does not seem to qualify the selection objct, so when you write Selection.PageSetup (ie) and start applying changes, it is applied to the Document already open in Word, not the document you are handling from VBA.
I've looked around for the answer on MSDN and here, but to no luck. If anyone knows how to qualify this object, let me know. Thanks.
Basically,
create word handler
open attachment in word
Selection.WholeStory
With Selection.PageSetup
.LineNumbering.Active = False
.Orientation = wdOrientPortrait
/* etc */
End with
Since "Selection" cannot be qualified, all these changes get made to whatever is already open.
if numTextFiles >= 1 then
for each textFile in textFileNames
'Open text file in word
Set doc = WordApp.Documents.Open(outReportFullDir & "\" & textFile)
'Set the output name of word doc (change .txt to .docx)
reportWordName = left(textFile, len(textFile) - 4)
reportWordName = reportWordName & ".docx"
'Check if out word document already exists
preventOverwrite(outReportFullDir & "\" & reportWordName)
'Format Reports
formatReport()
'etc
_
Private Sub formatReport()
documents(docToFormat).select
Selection.WholeStory
'Added by Ryan to make single-spaced
WordBasic.OpenOrCloseParaBelow
WordBasic.OpenOrCloseParaBelow
Selection.Font.Name = "Courier New"
Selection.Font.Size = 8
With Selection.PageSetup
.MirrorMargins = False
.TwoPagesOnOne = False
.BookFoldPrinting = False
.BookFoldRevPrinting = False
.BookFoldPrintingSheets = 1
.GutterPos = wdGutterPosLeft
End With
End Sub
There is probably confusion between Word's selection object and Outlook's selection object.
Use
WordApp.Selection
i.e.
WordApp.Selection.WholeStory
WordApp.Selection.Font.Name = "Courier New"
etc.
(or e.g.
Dim sel as Word.Selection
Set sel = WordApp.Selection
sel.WholeStory
sel.Font.Name = "Courier New"
Set sel = Nothing
So that if WordApp is not in scope, you should be able to use something like
Set sel = doc.Application.Selection
)
Finally, if you can get away with using Word Range instead, I would do so (e.g. doc.Range or Doc.Content) and avoid the whole Selection thing.
Have you tried something like this? It looks like you're getting a proper reference to the correct document at one stage in the game.
if numTextFiles >= 1 then
for each textFile in textFileNames
'Open text file in word
Set doc = WordApp.Documents.Open(outReportFullDir & "\" & textFile)
'Set the output name of word doc (change .txt to .docx)
reportWordName = left(textFile, len(textFile) - 4)
reportWordName = reportWordName & ".docx"
'Check if out word document already exists
preventOverwrite(outReportFullDir & "\" & reportWordName)
'Format Reports
Call formatReport(doc)
'etc
Private Sub formatReport(ByRef doc)
documents(doc).select
Selection.WholeStory
'Added by Ryan to make single-spaced
WordBasic.OpenOrCloseParaBelow
WordBasic.OpenOrCloseParaBelow
Selection.Font.Name = "Courier New"
Selection.Font.Size = 8
With Selection.PageSetup
.MirrorMargins = False
.TwoPagesOnOne = False
.BookFoldPrinting = False
.BookFoldRevPrinting = False
.BookFoldPrintingSheets = 1
.GutterPos = wdGutterPosLeft
End With
End Sub