2012-10-17 97 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語句中。 –

相關問題