首页 > 解决方案 > 将第一段作为文件名

问题描述

我正在寻找一种将第一段(用户名)添加为 Filename.pdf 的方法。

我有将每个新页面保存为 .pdf 文件的代码。

现在我需要每个 .pdf 文件都是唯一的,用户名写在页面的第一段。

Sub SaveAsSeparatePDFs()
'Updated by Extendoffice 20180906
    Dim I As Long
    Dim xStr As String
    Dim xPathStr As Variant
    Dim xDictoryStr As String
    Dim xFileDlg As FileDialog
    Dim xStartPage, xEndPage As Long
    Dim xStartPageStr, xEndPageStr As String
    Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    If xFileDlg.Show <> -1 Then
        MsgBox "Please chose a valid directory", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    xPathStr = xFileDlg.SelectedItems(1)
    xStartPageStr = InputBox("Begin saving PDFs starting with page __? " & vbNewLine & "(ex: 1)", "Kutools for Word")
    xEndPageStr = InputBox("Save PDFs until page __?" & vbNewLine & "(ex: 7)", "Kutools for Word")
    If Not (IsNumeric(xStartPageStr) And IsNumeric(xEndPageStr)) Then
        MsgBox "The enterng start page and end page should be number format", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    xStartPage = CInt(xStartPageStr)
    xEndPage = CInt(xEndPageStr)
    If xStartPage > xEndPage Then
        MsgBox "The start page number can't be larger than end page", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    If xEndPage > ActiveDocument.BuiltInDocumentProperties(wdPropertyPages) Then
        xEndPage = ActiveDocument.BuiltInDocumentProperties(wdPropertyPages)
    End If
    For I = xStartPage To xEndPage
        ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & Selection.Paragraphs(1).Range.Select & I & ".pdf", _
        wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportFromTo, I, I, wdExportDocumentWithMarkup, _
        False, False, wdExportCreateHeadingBookmarks, True, False, False
    Next
End Sub

的部分Selection.Paragraphs(1).Range.Select需要是我保存为 pdf 的每一页的第一段。

标签: vbams-word

解决方案


如果我正确理解了您的问题,那么您将用户名作为每页的第一段。

在这种情况下,我会选择这样的东西:

Dim rg As Range, username As String

For i = xStartPage To xEndPage

    Set rg = Activedocument.GoTo(wdGoToPage, wdGoToAbsolute, i)
    Set rg = rg.Paragraphs(1).Range
    rg.Select                                       #<= select for testing only
    username = Replace(rg.Text, vbCr, vbNullString) #<= replacing the paragraph sign at the end with nothing
    
    ActiveDocument.ExportAsFixedFormat xPathStr & "\Page_" & username & i & ".pdf", _
    wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportFromTo, i, i, wdExportDocumentWithMarkup, _
    False, False, wdExportCreateHeadingBookmarks, True, False, False
Next

推荐阅读