Open and print a section of word document as pdf

StephenBart

New Member
Joined
Jun 22, 2023
Messages
15
Office Version
  1. 365
Platform
  1. Windows
I have a macro enabled workbook to produce cost estimates for customer proposals. I have built a macro in cost estimate workbook to create a customer specific proposal in word from a word template that uses mail merge fields to pull in the data from various cells in the cost estimate workbook, and save the proposal with certain filename syntax and path based on cell values in the cost estimate workbook. The macro works great.

Sub CreateVIProposal()
'
' Creates Proposal Document for JPVI
'
Dim iApp As Word.Application
Dim iDoc As Word.Document
Dim FileName As String
Dim Path As String
Path = Range("c58") & "\"
FileName = Range("c61")
Set iApp = CreateObject("Word.Application")
iApp.Visible = True
iApp.Activate
Set iDoc = iApp.Documents.Add(Template:="U:\1000 ADMIN\1990 Templates\PROP_to_LlllFf_by_BartSt_re_CustNa-Street-Cit_RS_nx_YYYYMMDD_rev1.dotm", NewTemplate:=False, DocumentType:=0)
iDoc.SaveAs2 FileName:=Path & FileName & ".docm", FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End Sub

I need a macro in the cost estimate work book to open the macro enabled word document created above, in so doing update the merge fields, and then I would like to save a pdf of section s5 only (I use section breaks in the word document) the pdf will be saved in the same path but with different filename FileName = Range("c62"). I would like the word document to remain open and idealy navigated to s5.

Can anyone help me:)
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
Note that this line has an incompatible file extension and file format:

VBA Code:
iDoc.SaveAs2 FileName:=Path & FileName & ".docm", FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False

It should be this:
VBA Code:
    iDoc.SaveAs2 FileName:=Path & FileName & ".docm", FileFormat:=wdFormatXMLDocumentMacroEnabled, AddToRecentFiles:=False

I need a macro in the cost estimate work book to open the macro enabled word document created above, in so doing update the merge fields, and then I would like to save a pdf of section s5 only (I use section breaks in the word document) the pdf will be saved in the same path but with different filename FileName = Range("c62"). I would like the word document to remain open and idealy navigated to s5.

Try this, although the GoTo to section 5 doesn't work for me - the cursor stays at the first character of the document.

VBA Code:
ublic Sub Open_Doc_and_Save_Section5_As_PDF()

    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim FileName As String
    Dim PDFfileName As String
    Dim Path As String
    
    Path = Range("C58").Value & "\"
    FileName = Range("C61").Value
    PDFfileName = Range("C62").Value
    
    'Set WordApp = CreateObject("Word.Application")
    Set WordApp = New Word.Application
    
    With WordApp
        .Visible = True
        .Activate
        Set WordDoc = .Documents.Open(FileName:=Path & FileName & ".docm")
    End With
    
    With WordDoc
        .GoTo What:=wdGoToSection, Which:=wdGoToFirst, Count:=5, Name:=""
        .Sections(5).Range.ExportAsFixedFormat OutputFileName:=Path & PDFfileName & ".pdf", ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True
    End With

End Sub
 
Upvote 0
HI John,

I cant tell you how thankful I am for your help. I have no training in VBA and fumble around. The correction you pointed out the file extension /format and the VBA code you provided work perfectly. You have saved me hours (days lol) of trial and error and given we generate hundreds of proposals from cost estimates this has made that task so effortless. THANK YOU SO MUCH !!!!

Stephen
 
Upvote 0
Section 5 of the document is 2 pages long. I noticed when the macro prints Section 5 it produces a 3 page pdf, the 2 content pages plus an extra blank page. When I print s5 directly from the word document specifying s5 as the print range it produces a 2 page pdf as expected. Any ideas?

Thanks again.
 

Attachments

  • 1708587743395.png
    1708587743395.png
    57.8 KB · Views: 2
Upvote 0
Sorry - in the original post i referred to s5, since then i re-ordered the pages in the document so it is actually s4 in my code (s5 in your code). the macros above in the word template and the NASU code produces the 2-page pdf output.
 
Upvote 0
Section 5 of the document is 2 pages long. I noticed when the macro prints Section 5 it produces a 3 page pdf, the 2 content pages plus an extra blank page. When I print s5 directly from the word document specifying s5 as the print range it produces a 2 page pdf as expected. Any ideas?

This also happens with my test document. The Section 5 content is followed by a Section Break (Continuous) and the Section 6 content, all on 1 page. The export produces a PDF with Section 5 on page 1 and a blank page 2. Oddly, page 2 is slightly wider than page 1.

The first macro gets the Section 5 range, but I discovered this includes the Section Break (Continuous) character. For some reason, Word's PDF exporter is interpreting this character as 'start a new page'.

Here is a modified macro which fixes the problems in the first macro. If the last character in Section 4 is a Section Break (Continuous) or Section Break (Next Page) character it omits that character. As a result, the PDF contains only the Section 4 content, without the blank page. The cursor is also positioned at the start of Section 4 in the Word document.

VBA Code:
Public Sub Open_Doc_and_Save_Section_As_PDF()

    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim PDFsection As Word.Range
    Dim FileName As String
    Dim PDFfileName As String
    Dim Path As String
   
    Path = Range("C58").Value & "\"
    FileName = Range("C61").Value
    PDFfileName = Range("C62").Value
   
    'Set WordApp = CreateObject("Word.Application")
    Set WordApp = New Word.Application
   
    With WordApp
        .Visible = True
        .Activate
        Set WordDoc = .Documents.Open(FileName:=Path & FileName & ".docm")
    End With
   
    'Get Section 4 for exporting to PDF
   
    Set PDFsection = WordDoc.Sections(4).Range
   
    'If the last character in this section is a Section Break (Continuous or Next Page) (ASCII 12) then adjust the PDFsection range by 1 character to exclude it
   
    If Asc(PDFsection.Characters.Last) = 12 Then
        'PDFsection.Select  'the Selection includes the Section Break character
        Set PDFsection = WordDoc.Range(PDFsection.Start, PDFsection.End - 1)
        'PDFsection.Select   'the Selection now doesn't include the Section Break character
    End If
   
    PDFsection.ExportAsFixedFormat OutputFileName:=Path & PDFfileName & ".pdf", ExportFormat:=wdExportFormatPDF, OpenAfterExport:=True, Item:=wdExportDocumentContent

    PDFsection.Collapse wdCollapseStart
    PDFsection.Select
   
    WordApp.Windows(1).ScrollIntoView PDFsection, True

End Sub

The problem with the Section Break character can be seen if you delete the comment character at the start of the two PDFsection.Select lines and step through the code using F8 in the VBA editor.
 
Last edited:
Upvote 0
I am so glad it wasn't me doing something stupid. It works perfectly -THANK YOU (again)
 
Upvote 0

Forum statistics

Threads
1,215,077
Messages
6,122,991
Members
449,094
Latest member
masterms

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top