MS Word将每个页面保存为单独的PDF文档,该文档以文档中的特定文本命名

时间:2012-10-17 16:04:17

标签: pdf word-vba

我想转换Microsoft Excel发票数据表并填充邮件合并模板,一旦合并,我需要拆分每张发票并将其保存为pdf。

下面的代码执行我想要的但是将它们保存为1,2,3等。我想使用的名称是在文档上找到的发票编号(每个页面的前8个字符,不包括标题)。< / p>

这就是我现在的代码:

 Sub BreakOnPage()
     Selection.HomeKey Unit:=wdStory
     ' 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
     Selection.HomeKey Unit:=wdStory
     Selection.EndKey Unit:=wdStory
     Selection.TypeBackspace
     Selection.Delete Unit:=wdWord, Count:=1
     Selection.Delete Unit:=wdCharacter, Count:=1

     Dim strInvoiceNumber As String
     Selection.HomeKey Unit:=wdStory
     With Selection.Find
     .ClearFormatting
     Text:="^#^#^#^#^#^#^#^#"
     .Forward = True
     .MatchWildcards = False
     .Execute
     End With

     ' Defines the DocNum

     strInvoiceNumber = Selection.Text


     ' Exports the document to a pdf file and saves in sequence starting at 1 and closes the word document without saving

     ActiveDocument.ExportAsFixedFormat OutputFileName:= _
     "C:\Users\MLock\Documents\MacrosDocs\" & strInvoiceNumber & ".pdf", ExportFormat:= _
     wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
     wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
     Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
     CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
     BitmapMissingFonts:=True, UseISO19005_1:=False


     ActiveDocument.Close savechanges:=wdDoNotSaveChanges

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

如何在此处设置PDF文档的名称?

1 个答案:

答案 0 :(得分:2)

因此,您必须在页面上找到发票号并将其分配给变量,然后您可以使用该变量替换docnum。

执行查找的两种方法是使用Selection.Find,执行查找,然后将变量分配给Selection.Text。这可能是最简单的。

您还可以使用正则表达式,捕获反向引用中的前8个字符,然后使用它。

如果您需要,我可以澄清这些要点,不确定您的专业水平。

这里有一些代码可以完成我认为你想要做的事情。我假设Selection.HomeKey单位:wdStory指的是包​​含发票号的文件。

Sub BreakOnPage()
    Dim strInvoiceNumber as String
    Selection.HomeKey Unit:=wdStory
    With Selection.Find
        .ClearFormatting
        .Text:="^#^#^#^#^#^#^#^#"
        .Forward = True
        .MatchWildcards = False
        .Execute
    End With

现在将选择您的8位数发票号码。将变量strInvoiceNumber分配给Selection.Text,如下所示:

strInvoiceNumber = Selection.Text

现在在ExportAsFixedFormat语句中使用strInvoiceNumber而不是DocNum。

祝你好运。