使用最后一段中的文本字符串保存word文件的宏

时间:2014-07-11 16:00:13

标签: vba ms-word word-vba

我们收到一张包含发票的Word文档。该文档可以是可变数量的页面。文档中的每个页面代表一张发票。每页的最后一段包含一个唯一的编号。这个唯一的数字总是以相同的三位开头,让我们称之为" 123"。整个数字的长度可变。

宏应该在每个分页符处创建一个新的Word文档,并根据该页面上的上述唯一编号创建新的Word文档。发票永远不会超过一页。每个页面都有一张图片标题,还有一个链接字段,用于从单独的Excel文档中提取信息。

我看过各种帖子。我不能让他们正确地结合起来。我已经考虑过将每个页面上的唯一编号放在表单字段中并在每个页面上搜索表单字段,但我还没有能够远程构建任何内容。

我从以下代码开始:

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 

简而言之,我需要以某种方式将.SaveAs FileName:="设置为:

  1. 查找页面上的最后一段并将其用作文件名。
  2. 查找以字符串开头的段落(例如:" 123"),但该段的长度可变。
  3. 我更喜欢选项1,因为在某些情况下可能会有其他段落以" 123"开头。

1 个答案:

答案 0 :(得分:0)

简短的回答是:

ActiveDocument.Paragraphs.Last.Range.Text

类似于:

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