locked
Mail Merge VBA help RRS feed

  • Question

  • Hi All,

    I have the following peice of code and was wondering is there anyway i can get each item to be saved from one the fields within each document? I have an email address field in the mail merge document that i would like to be used as the document name when saved. Here is my code so far. I no i have to change the saveas part to point to something in the document but not sure how to get it to look at each mail merge document and pull our the email address field and use it as part of the saveas line...Thanks for looking.

    Sub SaveRecsAsFiles()
    ' Convert all sections to Subdocs
    AllSectionsToSubDoc ActiveDocument
    'Save each Subdoc as a separate file
    SaveAllSubDocs ActiveDocument
    End Sub


    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


    Sub SaveAllSubDocs(ByRef doc As Word.Document)
    Dim subdoc As Word.Subdocument
    Dim newdoc As Word.Document
    Dim docCounter As Long
    docCounter = 1
    'Must be in MasterView to work with
    'Subdocs as separate files
    doc.ActiveWindow.View = wdMasterView
    For i = 1 To oblist.Tables(1).Rows.Count
    Set DocName = oblist.Tables(1).Cell(i, 1).Range
    DocName.End = DocName.End - 1

    For Each subdoc In doc.Subdocuments
    Set newdoc = subdoc.Open
    'Remove NextPage section breaks
    'originating from mailmerge
    RemoveAllSectionBreaks newdoc
    With newdoc
    .SaveAs FileName:="MergeResult" & CStr(docCounter)
    .Close
    End With
    docCounter = docCounter + 1
    Next subdoc
    End Sub

    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

    The mail merge field is want to be used as the name is e-mail address

    Thanks

    Thursday, September 6, 2012 3:21 PM

All replies