2012-10-17 32 views
0

我想要转换发票数据的Microsoft Excel表格并填充邮件合并模板,并且一旦它合并,我需要分离每个发票和将其保存为pdf。MS Word将每个页面另存为单独的PDF文档,并以文档内的特定文本命名

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

这是我的代码看起来像现在:

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文档的名称?

回答

2

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

执行查找的两种方法是使用Selection.Find,执行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 

而现在使用strInvoiceNumber在ExportAsFixedFormat声明,而不是DocNum。

祝你好运。

+0

零专业知识,我将不胜感激任何额外的援助,你可以提供。第一个选项似乎很棒。什么是下一个步骤? –

+0

再次感谢你,以Text开头的行:=“^#...给我编译错误 –

+0

你需要在Text之前的一段时间,所以它被包含在With语句中。 –

相关问题