Using Macro to split word document, how do I specify name?

3.1k views Asked by At

I've tried looking for this on here and can't see an answer so thought I'd ask, apologies if this is a duplicate.

I'm using a mail merge to fill in a table in Word 2010. This created hundreds of pages of the same table but with different data in each one. I then use a Macro to split the word document into individual documents per page. My knowledge of Macros is very limited, but I've got it working, and I know how to amend the name if I just wanted a standard numbered thing, but what I want is for it to use one of the fields of the table as the name, so they'll all have their identifying number as their file name.

This is the code I've got for the macro:

Sub BreakOnPage()
   ' Used to set criteria for moving through the document by page.
   Application.Browser.Target = wdBrowsePage

   For i = 1 To ActiveDocument.BuiltInDocumentProperties("Number of Pages")

      'Select and copy the text to the clipboard.
      ActiveDocument.Bookmarks("\page").Range.Copy

      ' Open new document to paste the content of the clipboard into.
      Documents.Add
      Selection.Paste
' Removes the break that is copied at the end of the page, if any.
      Selection.TypeBackspace
      ChangeFileOpenDirectory "F:\MyWork"
      DocNum = DocNum + 1
      ActiveDocument.SaveAs FileName:="test_" & DocNum & ".doc"
      ActiveDocument.Close

      ' Move the selection to the next page in the document.
      Application.Browser.Next
   Next i
   ActiveDocument.Close savechanges:=wdDoNotSaveChanges
End Sub

But I have no idea how to make it pick up the field in the document. Any help would be very much appreciated!

Also, when this splits it into individual documents it seems to add a blank page to the bottom of it, so when I open one of the files I have my table but then a blank page under that, and I can't figure out how to get rid of that either, so tips on that would be a huge help too.

1

There are 1 answers

0
Michael On

You didn't specify which cell you needed, but this should get you started:

Dim sCellText As String
sCellText = ActiveDocument.Tables(1).Rows(1).Cells(1).Range
sCellText = Left$(sCellText, Len(sCellText) - 2)

ActiveDocument.SaveAs FileName:="sCellText & ".doc"

This will save the document as the value of the first cell in the first row