1
votes

We receive a Word document containing invoices. The document can be a variable number of pages. Each page in the document represents an invoice. The last paragraph of each page contains a unique number. That unique number always starts with the same three digits, let's call it "123". The entire number is variable in length.

The macro should create a new Word document at each page break and title that new Word document based on the aforementioned unique number on that page. Invoices will never be longer than one page. Each page has a picture in it's header, along with a linked field that pulls information from a separate Excel document.

I have seen various postings. I cannot get them to combine properly. I've thought about putting the unique number on each page in a form field and searching for the form field on each page, but I haven't been able to construct anything remotely close.

I started with the following code:

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 "C:\"
      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 

In short, I need to somehow set the .SaveAs FileName:=" to either:

  1. Look for the last paragraph on the page and use that as the file name.
  2. Look for the paragraph that starts with a string (example: "123"), but that paragraph is variable in length.

I prefer option 1 because there could be other paragraphs in some cases that start with "123".

1

1 Answers

0
votes

The short answer is:

ActiveDocument.Paragraphs.Last.Range.Text

So something like:

Dim lastParagraphText As String
lastParagraphText = ActiveDocument.Paragraphs.Last.Range.Text
lastParagraphText = Left$(lastParagraphText, Len(lastParagraphText) - 1)
ActiveDocument.SaveAs FileName:="test_" & lastParagraphText & ".doc"