Convert files to PDF (solved)

BrianB

Well-known Member
Joined
Feb 17, 2003
Messages
8,127
Here is some code that automatically converts files to pdf. Hopefully there is enough information that you can adapt it to your personal needs. This message contains a version for Excel files only, the next message gives a way of combining different types of file (.xls/.doc/.txt etc.)
Rich (BB code):
'=============================================================================
'-  CODE TO MAKE A PDF FILE USING PDF995 APPLICATION
'-  BY WRITING TEXT FILE 'pdf995.ini' -
'-  ** Version 1 : EXCEL WORKSHEET(S) FROM A SINGLE WORKBOOK
'-  I am using the paid for version of PDF995 with no advertising
'-  Brian Baulsom April 2010
'=============================================================================
'-     PDF995 is free from http://www.pdf995.com/download.html
'- It mimics a printer and is normally used by an application as such -
'- when it prompts for a .pdf file name instead of printing.
'-
'-     There is a separate free utility 'pdfEdit.exe' that enables a whole
'- host of possible output options. It works by changing the 'pdf995.ini' file
'- which is installed by the application (you will need to find where).
'- I used it to discover the parameters required. If you need a variety of
'- output scenarios, this is for you. Part of the purpose of this code is to
'- give the basics to set up your own personal output option. So you can do the same.
'-
'-     This code is to set up a few common scenarios so they automatically make
'- a .pdf file with no user intervention. The required scenario is selected
'- and set up by changing the code where necessary. It can be run from any
'- Microsoft Office application (eg. amend 'SelectedSheets' to 'ActiveDocument'
'- in Word) and could be used in a Visual Basic project.
'-
'- The code deletes the previous version of 'pdf995.ini'
'- The code checks the date/time of the output file to ensure the process
'- is finished, except when using the PDF995 Save As dialogue method.
'- Some parameters are automatically added by PDF995
'- PDF995 overwrites files without warning. Some checking is done here
'- but need to take care.
'-----------------------------------------------------------------------------
'- ** There are some parameter details at the end of the code ***
'=============================================================================
Dim PDF995ini As String
Dim MyActivePrinter As String
Dim OutPutFile As String
Dim OutPutFolder As String
Dim InitialDir As String              ' used with Save As dialogue & 'Output File="" '
'Dim UserFile As String                ' output pdf not used here
'Dim Launch As String                 ' Set by PDF995. Same as User File (Auto Launch=1)
'Dim DocumentName As String           ' Set by PDF995. Source document file name
Dim MyOutputScenario As String        ' different output options
Dim MyFileDateTime As Date
Dim wb As String
Dim CheckFile As String               ' file name use in Wait loop
Dim CheckCount As Integer             ' count tries to timeout
'=============================================================================
'- MAIN ROUTINE
'=============================================================================
Sub MAKE_PDF_FROM_EXCEL()
    '*************************************************************************
    '- USER SETTINGS
    '*************************************************************************
    '- SELECT SCENARIO (amend as required)
    MyOutputScenario = "Normal"       ' pdf = workbook file name & folder.
    'MyOutputScenario = "Folder\File"   ' different folder and/or file name
    'MyOutputScenario = "PromptForFile" ' use Save As dialog & initial folder set
    '*************************************************************************
    OutPutFile = ""
    OutPutFolder = ""
    MyActivePrinter = Application.ActivePrinter
    '=========================================================================
    '- NEW BASIC .INI FILE
    PDF995ini = "C:\Program Files (x86)\pdf995\res\pdf995.ini"
    Kill PDF995ini
    '-------------------------------------------------------------------------
    Open PDF995ini For Append As 1
        Print #1, "[Parameters]"
        Print #1, "Install=1"
        Print #1, "Quiet=0"
        Print #1, "Use GPL Ghostcript=1"
        Print #1, "AutoLaunch=1"           ' =0 to not run Acrobat at the end
        '---------------------------------------------------------------------
        '- SET OUTPUT FILE & OUTPUT FOLDER
        Select Case MyOutputScenario
            Case "Normal"                           ' all selected worksheets
                OutPutFile = "SAMEASDOCUMENT"
                OutPutFolder = ActiveWorkbook.Path
            Case "Folder\File"                      ' all selected worksheets
                OutPutFile = "F:\PDF Test.pdf"      ' needs full path
                OutPutFolder = "F:"                 ' no final "\"
            Case "PromptForFile"
                OutPutFile = ""                     ' PDF995 runs Save As
                InitialDir = "F:\test"              ' base Save As folder
            Case Else
                MsgBox ("Scenario " & MyOutputScenario & " is not a valid name")
                Exit Sub
        End Select
        '---------------------------------------------------------------------
        '- ADD PARAMETERS TO THE INI FILE
        If OutPutFile = "" Then         ' PDF995 will run the Save As dialog
            Print #1, "OutPut File="
            Print #1, "Initial Dir=" & InitialDir
        Else
            Print #1, "OutPut File=" & OutPutFile
        End If
        '---------------------------------------------------------------------
        If OutPutFolder <> "" Then Print #1, "Output Folder=" & OutPutFolder
        '---------------------------------------------------------------------
    Close #1
    '=========================================================================
    '- CHECK IF FILE ALREADY EXISTS
    wb = ActiveWorkbook.Name
    CheckFile = IIf(OutPutFile = "SAMEASDOCUMENT", ActiveWorkbook.Path & "\" _
        & Left(wb, Len(wb) - 4) & ".pdf", OutPutFile)
    f = Dir(CheckFile)
    If f <> "" Then
        rsp = MsgBox(CheckFile & vbCr & " already exists and will be replaced.", vbOKCancel)
        If rsp = vbCancel Then
            Application.ActivePrinter = MyActivePrinter
            Exit Sub
        End If
    End If
    '=========================================================================
    '- PRINT SELECTED WORKSHEET (changes Excel ActivePrinter)
    MyFileDateTime = Now            ' TIME FILE SETUP STARTS
    ActiveWindow.SelectedSheets.PrintOut Collate:=True, ActivePrinter:="PDF995"
    '-------------------------------------------------------------------------
    '- WAIT UNTIL THE NEW OUTPUT FILE EXISTS
    CheckCount = 1
    If CheckFile <> "" Then
        Do
            Application.Wait Now + TimeValue("00:00:02")  ' wait 2 seconds
            CheckCount = CheckCount + 1
        Loop While FileDateTime(CheckFile) <= MyFileDateTime _
            And CheckCount < 15     ' 15 x 2 seconds = 30 seconds and give up
        '=====================================================================
        '- RESET THE ACTIVE PRINTER
        Application.ActivePrinter = MyActivePrinter
        MsgBox ("File Saved " & vbCr & CheckFile & vbCr _
            & IIf(CheckCount > 14, " Took maximum time to run" & vbCr & "Please check the file", ""))
    End If
    '-------------------------------------------------------------------------
End Sub
'=============================================================================
'===========================================================================================================
'- SOME PARAMETER DETAILS (there are loads more possible depending on functions required)
'- "not required" = automatic addition by PDF995 depending on other parameters.
'===========================================================================================================
' AutoLaunch=
' 0                 - no display of .pdf when finished
' 1                 - Automaticall display PDF in default app. after printing (eg.Acrobat)
'-----------------------------------------------------------------------------------------------------------
' Output File=
'                    - (left blank) uses Save As dialog
'  1                 - incremented file name starting at this number (eg. 1.pdf, 2.pdf..)
'                      PDF995 automatically increments this number & changes other parameters if it exists
'                     (Not tested. Saved to 'Initial Dir =' as far as I can tell)
' SAMEASDOCUMENT     - auto name & save in default folder ..\pdf995\output
'                     or Output Folder if set (sets 'User File= ...  .pdf ')
' F:\test\test.pdf   - eg. uses same file name set for all output
'-----------------------------------------------------------------------------------------------------------
' Initial Dir=
' F:\test            - eg. for Save As dialog
'-----------------------------------------------------------------------------------------------------------
' Output Folder=
' F:\test            - eg. uses this folder instead of default '..\pdf995\output'
'                      use with 'Output File=SAMEASDOCUMENT'
'-----------------------------------------------------------------------------------------------------------
' Fixed Dir=
' F:\test            - eg. Save As opens at this folder use with AutoLaunch=1
'-----------------------------------------------------------------------------------------------------------
' Document Name = (Not required)
' book1.xls          - eg. source document
'-----------------------------------------------------------------------------------------------------------
' Combine Documents=
' 1                 - to combine consecutively "printed" documents into 1 .pdf (from any application !!)
'                     they are added individually so can stop\start any time
' 0                 - does not combine documents (default value so not usually needed)
'-----------------------------------------------------------------------------------------------------------
' Combine Last = (Not required if not combining)
' 0                               - does not combine with previous print job
' 1                               -   combines with previous print job
'-----------------------------------------------------------------------------------------------------------
' User File = (Not required.automatic by PDF995)
' F:\test\test.pdf   - eg. Don't know what this is for.
'-----------------------------------------------------------------------------------------------------------
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
Code:
'=============================================================================
'-  EXCEL CODE TO MAKE A PDF FILE USING PDF995 APPLICATION
'-  BY WRITING TEXT FILE 'pdf995.ini' -
'-  ** Version 2 : COMBINING MIXED EXCEL-WORD-TEXT FILES TO SINGLE PDF
'-  I am using the paid for version of PDF995 with no advertising
'=============================================================================
'-  This version makes a PDF file from Excel, Word, and Text files.
'-  Each type requires a different method. Could probably add non-MS Office types.
'-  Once pdf995.ini is set to combine files PDF995 makes the necessary changes.
'
'-  This development version uses hard-coded file names - it is an easy task to
'-  use another kind of list eg. in a worksheet or word document.
'
'-  Uses the file suffix to distinguish file types and "print" as required
'-  Please see the Excel Version 1 for code specific to that application and
'-  more basic information.
'-  I have added code to open the pdf file at the end.
'- 'pdfEdit.exe' can add page numbers bottom centre to pdf named in pdf995.ini
'-  Brian Baulsom April 2010
'=============================================================================
Option Base 1
Public Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Dim FileList(5, 2)              ' Array list of files to make pdf
                                ' Excel needs 2 items - Workbook\Worksheet
Dim MyFile As String            ' add file name
Dim FileType As String          ' xls, doc, txt
Dim FileCount As Integer        ' total files
Dim CurrentFile As Integer      ' current file in loop
Dim SourceFolder As String      ' my source files are all in this folder.
'------------------------------------------------------------------------------
Dim PDF995ini As String
Dim ExcelPrinter As String
Dim OutPutFile As String        ' set to "" to get the Save As dialogue box
'Dim InitialDir As String       ' not used unless you want Save As dialog
'Dim UserFile As String         ' (not used here) pdf output file
'Dim LaunchFile As String       ' Set by PDF995. Same as User File (Auto Launch=1)
'Dim DocumentName As String     ' Set by PDF995. Source document file name
Dim CancelProcess As Boolean
Dim rsp
'=============================================================================
'- MAIN ROUTINE
'=============================================================================
Sub MAKE_COMBINED_PDF()
    '*************************************************************************
    '- USER SETTINGS
    '*************************************************************************
    '- pdf995.ini LOCATION
    PDF995ini = "C:\Program Files (x86)\pdf995\res\pdf995.ini"
    '-------------------------------------------------------------------------
    '- OUTPUT FILE
    OutPutFile = ThisWorkbook.Path & "\" & "MyCombined.pdf"
    '-------------------------------------------------------------------------
    '- LIST OF FILES TO BE COMBINED (Full paths required here)
    '- Excel worksheets need 2 fields.
    SourceFolder = "F:\test\"
    FileList(1, 1) = SourceFolder & "book1.xls": FileList(1, 2) = "Sheet1"
    FileList(2, 1) = SourceFolder & "book1.xls": FileList(2, 2) = "Sheet2"
    FileList(3, 1) = SourceFolder & "book1.xls": FileList(3, 2) = "Sheet3"
    FileList(4, 1) = SourceFolder & "TestDoc.doc"
    FileList(5, 1) = SourceFolder & "TestTxt.txt"
    '*************************************************************************
    '- CHECK IF THE OUTPUT FILE ALREADY EXISTS. OPTION TO CANCEL OR CONTINUE
    If Dir(OutPutFile) <> "" Then
        rsp = MsgBox(OutPutFile & vbCr & "already exists and will be replaced.", vbOKCancel)
        If rsp = vbCancel Then Exit Sub
    End If
    '-------------------------------------------------------------------------
    '- GET EXCEL DEFAULT PRINTER (WORD WILL USE PDF995 WITHOUT CHANGING)
    ExcelPrinter = Application.ActivePrinter
    '------------------------------------------------------------------------
    CancelProcess = False
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    '========================================================================
    '- DELETE OLD pdf995.ini FILE
    Kill PDF995ini
    '------------------------------------------------------------------------
    '- (PDF995 makes subsequent changes)
    Open PDF995ini For Append As 1
        Print #1, "[Parameters]"
        Print #1, "Install=1"
        Print #1, "Quiet=0"
        Print #1, "Use GPL Ghostcript=1"
        Print #1, "Combine Documents=1"    ' set to combine documents
        Print #1, "Combine Last=0"         ' new batch. PDF995 changes it to 1
        Print #1, "AutoLaunch=0"           ' don't change (each doc runs Acrobat)
        Print #1, "Rotate Pages = 0"
        Print #1, "Conversion Parameters=-sDEVICE=pdfwrite -q -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.3 -dAutoRotatePages=/None -dNOPAUSE -dBATCH"
        Print #1, "Edit Rotate Pages=1"
        Print #1, "Output File=" & OutPutFile
    Close #1
    '=========================================================================
    '- LOOP THROUGH THE FILE LIST
    FileCount = UBound(FileList)
    For CurrentFile = 1 To FileCount
        MyFile = FileList(CurrentFile, 1)
        FileType = UCase(Right(MyFile, 3))
        If FileType = "XLS" Then
            ADD_WORKSHEET
        ElseIf FileType = "DOC" Then
            ADD_DOC
        ElseIf FileType = "TXT" Then
            ADD_DOC
        Else
            MsgBox (FileType & " this file type is not handled.")
            CancelProcess = True
        End If
        '--------------------------------------------------------------------
        If CancelProcess = True Then Exit For
        '--------------------------------------------------------------------
    Next
    '========================================================================
    '- FINISH  Reset Excel printer. Check for completion
    Application.ActivePrinter = ExcelPrinter
    '----------------------------------------------------
    If CancelProcess = False Then
        MsgBox ("All files added to " & OutPutFile)
    Else
        MsgBox ("Process cancelled with file " & MyFile)
    End If
    '------------------------------------------------------------------------
    Application.StatusBar = False
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationAutomatic
    '========================================================================
    '- OPEN THE PDF FILE IN THE DEFAULT APPLICATION (eg. Acrobat)
    rsp = ShellExecute(0, "OPEN", OutPutFile, "", "", 1)
    '------------------------------------------------------------------------
End Sub
'=============================================================================
'=============================================================================
'- SUBROUTINE : ADD WORKSHEET
'=============================================================================
Private Sub ADD_WORKSHEET()
    Dim wb As String
    Dim ws As String
    Dim SplitPath As Variant        ' Split path to get workbook name only
    '------------------------------------------------------------------------
    '- NEW WORKBOOK - GET WORKBOOK NAME FROM PATH
    '- If the previous document referred to this workbook it will be open
    If wb = "" Then     ' need to open another workbook
        SplitPath = Split(FileList(CurrentFile, 1), "\", -1, vbTextCompare)
        wb = SplitPath(UBound(SplitPath))   ' WORKBOOK NAME ONLY (NO PATH)
        Workbooks.Open Filename:=FileList(CurrentFile, 1), updatelinks:=False
    End If
    '------------------------------------------------------------------------
    '- ADD THE WORKSHEET TO THE PDF
    ws = FileList(CurrentFile, 2)
    Workbooks(wb).Worksheets(ws).PrintOut ActivePrinter:="PDF995"
    WAIT_FOR_FILE
    If CancelProcess = True Then Exit Sub
    '------------------------------------------------------------------------
    '- CHECK IF NEXT DOCUMENT IS IN THE SAME WORKBOOK
    If CurrentFile < FileCount Then    'stops possible error in the next line
        If FileList(CurrentFile + 1, 1) <> wb Then
            Workbooks(wb).Close savechanges:=False
            wb = ""
        End If
    End If
    '------------------------------------------------------------------------
End Sub
'-----------------------------------------------------------------------------
'=============================================================================
'- SUBROUTINE : ADD WORD DOCUMENT OR TEXT FILE (using Word)
'=============================================================================
Private Sub ADD_DOC()
    Dim WordApp As Object
    Dim WordDoc As Object
    '-------------------------------------------------------------------------
    '- OPEN WORD IN THE BACKGROUND
    Set WordApp = CreateObject("Word.Application")
    WordApp.Documents.Open Filename:=FileList(CurrentFile, 1)
    Set WordDoc = WordApp.ActiveDocument
    WordApp.Visible = False
    '-------------------------------------------------------------------------
    '- ADD THE WORD DOCUMENT TO THE PDF
    WordApp.WordBasic.FilePrintSetup Printer:="PDF995", _
      DoNotSetAsSysDefault:=1       ' = "do not set as the SYSTEM default"
    WordDoc.PrintOut
    WAIT_FOR_FILE
    '-------------------------------------------------------------------------
    '- CLOSE WORD
    WordDoc.Close savechanges:=False
    WordApp.Quit
    Set WordDoc = Nothing
    Set WordApp = Nothing
    '-------------------------------------------------------------------------
End Sub
'-----------------------------------------------------------------------------
 
'=============================================================================
'- SUBROUTINE : WAIT UNTIL THE OUTPUT FILE EXISTS ON DISK
'=============================================================================
Private Sub WAIT_FOR_FILE()
    Dim CheckCount As Integer
    Dim StatusMessage As String
    Dim MyFileDateTime As Date
    '-------------------------------------------------------------------------
    MyFileDateTime = Now            ' START TIME
    '-------------------------------------------------------------------------
    '- SHOW STATUS
    StatusMessage = "  Processing " & CurrentFile & " of " & FileCount _
        & " :  " & MyFile & " " & FileList(CurrentFile, 2)
    Application.StatusBar = StatusMessage
    '-------------------------------------------------------------------------
    On Error Resume Next
    CheckCount = 1
    Do
        Application.Wait Now + TimeValue("00:00:02")  ' wait 2 seconds
        CheckCount = CheckCount + 1
    Loop While FileDateTime(OutPutFile) <= MyFileDateTime _
        And CheckCount < 15     ' 15 x 2 seconds = 30 seconds and give up
    On Error GoTo 0
    '---------------------------------------------------------------------
    '- TIMEOUT MESSAGE
    If CheckCount > 14 Then
        rsp = MsgBox(CheckFile & " took maximum time to add." & vbCr _
              & "Please check target " & vbCr & OutPutFile, vbOKCancel)
        If rsp = vbCancel Then CancelProcess = True
    End If
    '---------------------------------------------------------------------
End Sub
'------- END OF WAIT_FOR_FILE ------------------------------------------------
 
Upvote 0
VERSION 3 : TO PRINT EACH WORKSHEET PAGE TO A SEPARATE FILE
Uses normal Excel print method to get pages.

Code:
'=============================================================================
'-  CODE TO MAKE A PDF FILE USING PDF995 APPLICATION
'-  BY WRITING TEXT FILE 'pdf995.ini' -
'-    ** Version 3 **
'-  EACH WORKSHEET PAGE TO A SEPARATE PDF FILE
'-  PDF995 overwrites files of the same name with no error message
'-  Brian Baulsom May 2010
'=============================================================================
'- Please see versions 1 & 2 in this thread for other use & more details
'- Each "print page"  needs a new pdf995.ini
'- This version uses a subroutine to remake the pdf995.ini and "print"
'=============================================================================
'- TO OPEN THE FOLDER AT THE END
Private Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
'-----------------------------------------------------------------------------
'- variables for Excel pages
'- new files added to the same folder as the workbook
Dim ws As Worksheet
Dim MyPage As Integer       ' page number
Dim TotalPages As Integer   ' total pages
Dim MyFolder As String      ' used for output folder\file name.pdf
Dim MyPDF                   ' pdf file name as worksheet (page number added)
'-----------------------------------------------------------------------------
'- variables for PDF995
Dim PDF995ini As String
Dim MyActivePrinter As String         ' existing printer. reset at the end.
Dim OutputFile As String              ' FINAL PDF FILE NAME
Dim UserFile As String                ' same as OutputFile
Dim OutPutFolder As String
'----------------------------------------------------------------------------
'- variables to check the pdf file has saved
Dim MyFileDateTime As Date
Dim CheckCount As Integer             ' count tries taken
'=============================================================================
'- MAIN ROUTINE
'=============================================================================
Sub WORKSHEET_PAGES_SEPARATE_PDFs()
    Set ws = ActiveSheet
    '*************************************************************************
    '***   USER SETTINGS                                                   ***
    '*************************************************************************
    '- PDF995.INI FILE LOCATION
    PDF995ini = "C:\Program Files (x86)\pdf995\res\pdf995.ini"
    MyPDF = ws.Name   ' generic pdf file name (page number will be added)
    '*************************************************************************
    '- OTHER SETTINGS
    MyActivePrinter = Application.ActivePrinter ' existing active printer
    MyFolder = ThisWorkbook.Path & "\"
    TotalPages = Application.ExecuteExcel4Macro("GET.DOCUMENT(50)")
    Application.Calculation = xlCalculationManual
    '=========================================================================
    '- LOOP TO GET WORKSHEET PAGES
    For MyPage = 1 To TotalPages
        OutputFile = MyFolder _
            & MyPDF & "-" & Format(MyPage, "00") & ".pdf"
        Application.StatusBar = "  Printing page " & MyPage & " of " & TotalPages
        MyFileDateTime = Now        ' TIME FILE SETUP STARTS
        '============
        PRINT_PAGE                  ' SUBROUTINE
        '============
    Next
    '=========================================================================
    '- FINISH
    MsgBox ("Done")
    Application.ActivePrinter = MyActivePrinter     ' reset to original printer
    Application.Calculation = xlCalculationManual
    Application.StatusBar = False
    '-------------------------------------------------------------------------
    '- OPEN THE FOLDER
    rsp = ShellExecute(0, "OPEN", MyFolder, "", "", 1)
    '------------------------------------------------------------------------
End Sub
'====== end of main routine ==================================================
 
'=============================================================================
'- SUBROUTINE : REMAKE pdf995.ini & PRINT THE PAGE
'=============================================================================
Private Sub PRINT_PAGE()
    On Error Resume Next
    UserFile = OutputFile
    '-------------------------------------------------------------------------
    Kill PDF995ini
    Open PDF995ini For Append As 1
        Print #1, "[Parameters]"
        Print #1, "Install=1"
        Print #1, "Quiet=0"
        Print #1, "Use GPL Ghostcript=1"
        Print #1, "AutoLaunch=0"           ' = not run Acrobat each time
        '---------------------------------------------------------------------
        '- OUTPUT FILE & FOLDER FROM VARIABLES
        Print #1, "OutPut File=" & OutputFile
        Print #1, "User File=" & UserFile
        '---------------------------------------------------------------------
    Close #1
    '-------------------------------------------------------------------------
    '- PRINT THE EXCEL PAGE
    ws.PrintOut From:=MyPage, To:=MyPage, Copies:=1, ActivePrinter:="PDF995"
    '-------------------------------------------------------------------------
    '- WAIT UNTIL THE NEW OUTPUT FILE EXISTS (MAX 30 SECONDS)
    CheckCount = 1
    Do
       Application.Wait Now + TimeValue("00:00:02")  ' wait 2 seconds
       CheckCount = CheckCount + 1
    Loop While FileDateTime(OutputFile) <= MyFileDateTime _
       And CheckCount < 15     ' 15 x 2 seconds = 30 seconds and give up
    '----------------------------------------------------------------------
    '- CHECK COUNTER
    If CheckCount >= 15 Then
       MsgBox ("Please check file " & OutputFile & " has been saved." & vbCr _
               & "It took the full 30 seconds. The macro will continue.")
    End If
    '--------------------------------------------------------------------------
End Sub
'=============================================================================
 
Last edited:
Upvote 0
Yet another Version to print ranges from a worksheet.
If you set the header rows etc. in Page Setup they will be repeated.

Rich (BB code):
'=============================================================================
'-  CODE TO MAKE A PDF FILE USING PDF995 APPLICATION
'-  BY WRITING TEXT FILE 'pdf995.ini' -
'=============================================================================
'-    ** Version 4 **
'-  SINGLE WORKSHEET *RANGES* TO SEPARATE PDF FILES
'-  Resets the Print_Area for each range and "prints"
'-  ref http://www.mrexcel.com/forum/showthread.php?p=2305936 (sample worksheet)
'-  Looks for non-blank cells in column A from start row of first range
'-  Looks for "TOTAL" in column C for last row of the range
'-  Looks for "END" in column A to finish
'-  No change to Private Sub PRINT_PAGE() from version 3
'-----------------------------------------------------------------------------
'-  PDF995 overwrites files of the same name with no error message
'-  Brian Baulsom May 2010
'=============================================================================
'- Please see versions 1,2 and 3 in this thread for other use & more details
'- Each "print page"  needs a new pdf995.ini
'- This version uses a subroutine to remake the pdf995.ini and "print"
'=============================================================================
'- TO OPEN THE FOLDER AT THE END
Private Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
'-----------------------------------------------------------------------------
'- variables for Excel pages (ranges)
Dim MyCell As Range         ' first row column A
Dim MyRange As Range        ' separate range to print
Dim StartRow As Long        ' first row of rnge
Dim LastRow As Long         ' last row of range
Dim FoundCell As Range      ' Find "TOTAL"
Dim Counter As Integer      ' count/file name
'- new files added to the same folder as the workbook
Dim ws As Worksheet
Dim MyPage As Integer       ' page number
Dim TotalPages As Integer   ' total pages
Dim MyFolder As String      ' used for output folder\file name.pdf
Dim MyPDF                   ' pdf file name as worksheet (page number added)
'-----------------------------------------------------------------------------
'- variables for PDF995
Dim PDF995ini As String
Dim MyActivePrinter As String         ' existing printer. reset at the end.
Dim OutputFile As String              ' FINAL PDF FILE NAME
Dim UserFile As String                ' same as OutputFile
Dim OutPutFolder As String
'----------------------------------------------------------------------------
'- variables to check the pdf file has saved
Dim MyFileDateTime As Date
Dim CheckCount As Integer             ' count tries taken
'=============================================================================
'- MAIN ROUTINE
'=============================================================================
Sub WORKSHEET_RANGES_TO_PDFs()
    Set ws = ActiveSheet
    '*************************************************************************
    '***   USER SETTINGS                                                   ***
    '*************************************************************************
    '- PDF995.INI FILE LOCATION
    PDF995ini = "C:\Program Files (x86)\pdf995\res\pdf995.ini"
    MyPDF = ws.Name   ' generic pdf file name (page number will be added)
    '*************************************************************************
    '- OTHER SETTINGS
    MyActivePrinter = Application.ActivePrinter ' existing active printer
    MyFolder = ThisWorkbook.Path & "\"
    TotalPages = Application.ExecuteExcel4Macro("GET.DOCUMENT(50)")
    Application.Calculation = xlCalculationManual
    '=========================================================================
    '- LOOP TO GET WORKSHEET PAGE RANGES
    '=========================================================================
    MyPage = 1      ' RANGE TREATED AS A SINGLE PAGE
    StartRow = 6    ' first row of first range
    Set MyCell = ws.Cells(StartRow, 1)
    Counter = 1
    '-------------------------------------------------------------------------
    '- MAIN LOOP
    Do
        '---------------------------------------------------------------------
        '- LAST ROW OF RANGE : FIND "TOTAL"
        Set FoundCell = Cells.Find(What:="TOTAL", After:=MyCell, _
            LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False)
        '----------------------------
        If FoundCell Is Nothing Then
            MsgBox ("Cannot find TOTAL row")
            Exit Sub
            '----------------------------
        Else
            '-----------------------------------------------------------------
            '- SET THE PRINT RANGE
            LastRow = FoundCell.Row + 1
            s = ws.Range(Cells(StartRow, "A"), Cells(LastRow, "L")).Address
            ws.PageSetup.PrintArea = s
            '-----------------------------------------------------------------
            '- PRINT THE RANGE
            OutputFile = MyFolder _
                & MyPDF & "-" & Format(Counter, "00") & ".pdf"
            Application.StatusBar = "  Printing RANGE " & Counter
            MyFileDateTime = Now        ' TIME FILE SETUP STARTS
            '============
            PRINT_PAGE                  ' SUBROUTINE
            Counter = Counter + 1
            '============
            '-----------------------------------------------------------------
            '- GET THE NEXT RANGE START (next non-empty cell)
            StartRow = StartRow + 1
            While CStr(ws.Cells(StartRow, 1).Value) = ""
                StartRow = StartRow + 1
            Wend
            '-----------------------------------------------------------------
            Set MyCell = ws.Cells(StartRow, 1)
            If MyCell.Value = "END" Then Exit Do
        End If
        '---------------------------------------------------------------------
    Loop
    '=========================================================================
    '- FINISH
    MsgBox ("Done")
    Application.ActivePrinter = MyActivePrinter     ' reset to original printer
    Application.Calculation = xlCalculationManual
    Application.StatusBar = False
    '-------------------------------------------------------------------------
    '- OPEN THE FOLDER
    rsp = ShellExecute(0, "OPEN", MyFolder, "", "", 1)
    '------------------------------------------------------------------------
End Sub
'====== end of main routine ==================================================
 
'=============================================================================
'- SUBROUTINE : REMAKE pdf995.ini & PRINT THE PAGE
'=============================================================================
Private Sub PRINT_PAGE()
    On Error Resume Next
    UserFile = OutputFile
    '-------------------------------------------------------------------------
    Kill PDF995ini
    Open PDF995ini For Append As 1
        Print #1, "[Parameters]"
        Print #1, "Install=1"
        Print #1, "Quiet=0"
        Print #1, "Use GPL Ghostcript=1"
        Print #1, "AutoLaunch=0"           ' = not run Acrobat each time
        '---------------------------------------------------------------------
        '- OUTPUT FILE & FOLDER FROM VARIABLES
        Print #1, "OutPut File=" & OutputFile
        Print #1, "User File=" & UserFile
        '---------------------------------------------------------------------
    Close #1
    '-------------------------------------------------------------------------
    '- PRINT THE EXCEL PAGE
    ws.PrintOut From:=MyPage, To:=MyPage, Copies:=1, ActivePrinter:="PDF995"
    '-------------------------------------------------------------------------
    '- WAIT UNTIL THE NEW OUTPUT FILE EXISTS (MAX 30 SECONDS)
    CheckCount = 1
    Do
       Application.Wait Now + TimeValue("00:00:02")  ' wait 2 seconds
       CheckCount = CheckCount + 1
    Loop While FileDateTime(OutputFile) <= MyFileDateTime _
       And CheckCount < 15     ' 15 x 2 seconds = 30 seconds and give up
    '----------------------------------------------------------------------
    '- CHECK COUNTER
    If CheckCount >= 15 Then
       MsgBox ("Please check file " & OutputFile & " has been saved." & vbCr _
               & "It took the full 30 seconds. The macro will continue.")
    End If
    '--------------------------------------------------------------------------
End Sub
'=============================================================================
 
Last edited:
Upvote 0
Hi Brian

I have a an Excel worksheet (template) It is used to create worksheets in the same workbook by employee name. So each worksheet tab will have firstname,lastname and staff no.

I have tried to make your script work by naming the saved PDF files by the worksheet names as this is used by the next part of our workflow. I have been able to do this with Adobe, but the org wants to use PDF995.

So is there a way using PDF995 to get the files automatically processed and named eg.
John Jones 9947006
Michael Smith 657384
Joanne Jones 445566

I have tried modifying my current adobe script with no success, I have also tried to merge yours (vers 3) and the other script with no success just many errors and debugs.

As you appear to be a wizard at PDF995 I thought I would ask the question. Hoping you might be able to help

cheers

Ron
 
Upvote 0
Brian

I forgot to mention within the workbook template there are three worksheets that dont need to be printed out. These are a menu, roster and the timesheet template.

I am able to provide you with the file if this would help.

thanks

Ron
 
Upvote 0
Yet another version then. Thank goodness for Copy/Paste I say :LOL:
Code:
'=============================================================================
'-    ** Version 5 **
'- SINGLE WORKSHEETS IN THE SAME WORKBOOK TO SEPARATE PDF FILES
'- Uses the same basic "print" sub routine as the other versions
'- Checks cell Z1 in each worksheet for "PRINT"
'=============================================================================
'- Please remember that Excel Page Setup does the formatting in the usual way
'- VERSION 1 can be used by holding Ctrl key to select multiple worksheets.
'- ... this does, however, number pages from 1 upwards for the whole set.
'- This version treats each worksheet as a separate entity.
'- *Here the "OutPutFolder" variable is set to the same as the workbook.
'=============================================================================
'- The method is to set the variable "MyPDFfileName" and "print" the worksheet.
'- The code concatenates OutputFolder & MyPDFfileName" & ".pdf"
'- *Here we make MyPDFfileName the same as the worksheet name.
'=============================================================================
'- There are many ways of deciding which worksheet(s) to print
'- eg. by checking sheet name, a cell value, or a separate list.
'-  - or remove If ..... End If to print them all.
'- If required sheets have the same content, we can check each sheet in the
'- workbook for a common cell value.
'- *Here my sheets are different - so I have set print ranges, and look at a
'-    cell (Z1) *outside the print range* to see if it contains "PRINT"
'=============================================================================
Private Declare Function ShellExecute Lib "Shell32.dll" Alias "ShellExecuteA" _
     (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Dim ws As Worksheet
Dim MyPDFfileName As String         ' string to customise .pdf file name
Dim PDF995ini As String             ' full path & \pdf995.ini
Dim MyActivePrinter As String
'- PDF995
Dim OutPutFolder As String          ' here set the same as the workbook
Dim OutputFile As String            ' PDF full path & file name
Dim UserFile As String              ' same as OutPutFile
Dim Launch As String                ' same as OutPutFile
'Dim DocumentName As String          ' Set by PDF995. Workbook name only
'-
Dim MyFileDateTime As Date          ' used to check timeout
Dim CheckFile As String             ' file name use in Wait loop
Dim CheckCount As Integer           ' count tries to timeout
'=============================================================================
'- MAIN ROUTINE - GET EACH WORKSHEET
'=============================================================================
Sub PDF_FILES_FROM_WORKSHEETS()
    Application.Calculation = xlCalculationManual
    '*************************************************************************
    '***   USER SETTINGS                                                   ***
    '*************************************************************************
    PDF995ini = "C:\Program Files (x86)\pdf995\res\pdf995.ini"
    OutPutFolder = ThisWorkbook.Path & "\"
    '*************************************************************************
    '- Save ActivePrinter to reset later
    MyActivePrinter = Application.ActivePrinter
    '=========================================================================
    '- LOOP TO CHECK EACH WORKSHEET
    '=========================================================================
    For Each ws In ActiveWorkbook.Worksheets
        '- CHECK CELL VALUE (NB. case sensitive)
        If ws.Range("Z1").Value = "PRINT" Then
            '-----------------------------------------------------------------
            '- PDF FILE NAME (could use a cell value)
            MyPDFfileName = ws.Name
            OutputFile = OutPutFolder & MyPDFfileName & ".pdf"
            '-----------------------------------------------------------------
            Application.StatusBar = _
                " Printing " & ws.Name & " --> " & MyPDFfileName
            MyFileDateTime = Now        ' TIME FILE SETUP STARTS
            '-----------------------------------------------------------------
            PRINT_WORKSHEET             ' SUBROUTINE
            '-----------------------------------------------------------------
        End If
    Next
    '=========================================================================
    '- FINISH
    MsgBox ("Done")
    Application.ActivePrinter = MyActivePrinter     ' reset to original printer
    Application.Calculation = xlCalculationManual
    Application.StatusBar = False
    '-------------------------------------------------------------------------
    '- OPEN THE OUTPUT FOLDER IN WINDOWS EXPLORER
    rsp = ShellExecute(0, "OPEN", OutPutFolder, "", "", 1)
    '------------------------------------------------------------------------
End Sub
'============= end of main routine ===========================================
'=============================================================================
'- SUBROUTINE : REMAKE pdf995.ini & "PRINT" THE WORKSHEET
'=============================================================================
Private Sub PRINT_WORKSHEET()
    On Error Resume Next
    '-------------------------------------------------------------------------
    Kill PDF995ini
    Open PDF995ini For Append As 1
        Print #1, "[Parameters]"
        Print #1, "Install=1"
        Print #1, "Quiet=0"
        Print #1, "Use GPL Ghostcript=1"
        Print #1, "AutoLaunch=0"           ' = not run Acrobat each time
        '---------------------------------------------------------------------
        '- OUTPUT FILE & FOLDER FROM VARIABLES
        Print #1, "OutPut File=" & OutputFile
        Print #1, "User File=" & OutputFile         ' same as OutPutFile
        Print #1, "Launch=" & OutputFile            ' same as OutPutFile
        '---------------------------------------------------------------------
    Close #1
    '-------------------------------------------------------------------------
    '- PRINT
    ws.PrintOut ActivePrinter:="PDF995"
    '-------------------------------------------------------------------------
    '- WAIT UNTIL THE NEW OUTPUT FILE EXISTS (MAX 30 SECONDS)
    CheckCount = 1
    Do
       Application.Wait Now + TimeValue("00:00:02")  ' wait 2 seconds
       CheckCount = CheckCount + 1
    Loop While FileDateTime(OutputFile) <= MyFileDateTime _
       And CheckCount < 15     ' 15 x 2 seconds = 30 seconds and give up
    '----------------------------------------------------------------------
    '- CHECK COUNTER
    If CheckCount >= 15 Then
       MsgBox ("Please check file " & OutputFile & " has been saved." & vbCr _
               & "It took the full 30 seconds. The macro will continue.")
    End If
    '--------------------------------------------------------------------------
End Sub
'=============================================================================
 
Upvote 0
Thanks Brian
Worked ok and gave me something to go on with. I am new to the board and have not been able to find how to attach code like all of you. So here is my modified code hoping it will be helpful to others. This allows exclusion of worksheets that you may not want to print. eg blank template worksheet (attendnace table, menu, etc)

Any tips on where i go to find out how to add vb code in separate window appreciated.

Thank you again Brian

'=============================================================================
'- MAIN ROUTINE - GET EACH WORKSHEET
'=============================================================================
Sub PDF_FILES_FROM_WORKSHEETSV5a()
Application.Calculation = xlCalculationManual
'*************************************************************************
'*** USER SETTINGS ***
'*************************************************************************
'sometimes (not always) it appears necessary to manually use PDF995 edit _
to set the Auto-Name the file save to different names.
PDF995ini = "C:\Program Files\pdf995\res\pdf995.ini"
OutPutFolder = ThisWorkbook.Path & "\Saved Files\"
'& ws.Name
'*************************************************************************

'- Save ActivePrinter to reset later
MyActivePrinter = Application.ActivePrinter

'=========================================================================
'- LOOP TO CHECK EACH WORKSHEET
'=========================================================================
'Brian's script select cell reference
'For Each ws In ActiveWorkbook.Worksheets
'- CHECK CELL VALUE (NB. case sensitive)
'If ws.Range("AR38").Value <> "PRINT" Then

'=========================================================================
'WORKING EXCLUSION SCRIPT FROM WORKING ADOBE. These worksheet pages do _
not need to be printed/converted to image. Only valid timesheets required.
'It also refers to only visible sheets else hidden causes error.

For Each ws In ActiveWorkbook.Worksheets
If ws.Visible = xlSheetVisible And ws.Name <> "MainMenu" _
And ws.Name <> "Attendance table" _
And ws.Name <> "Roster" Then

'-----------------------------------------------------------------
'- PDF FILE NAME (could use a cell value)
MyPDFfileName = ws.Name
OutputFile = OutPutFolder & MyPDFfileName & ".pdf"
'-----------------------------------------------------------------
Application.StatusBar = _
" Printing " & ws.Name & " --> " & MyPDFfileName
MyFileDateTime = Now ' TIME FILE SETUP STARTS
'-----------------------------------------------------------------
PRINT_WORKSHEET ' SUBROUTINE
'-----------------------------------------------------------------

End If
Next
'=========================================================================
'- FINISH
MsgBox ("Done")
Application.ActivePrinter = MyActivePrinter ' reset to original printer
Application.Calculation = xlCalculationManual
Application.StatusBar = False
'-------------------------------------------------------------------------
'- OPEN THE OUTPUT FOLDER IN WINDOWS EXPLORER
rsp = ShellExecute(0, "OPEN", OutPutFolder, "", "", 1)
'------------------------------------------------------------------------
End Sub
'============= end of main routine ===========================================
'=============================================================================
'- SUBROUTINE : REMAKE pdf995.ini & "PRINT" THE WORKSHEET
'=============================================================================
Private Sub PRINT_WORKSHEET()
On Error Resume Next
'-------------------------------------------------------------------------
Kill PDF995ini
Open PDF995ini For Append As 1
Print #1, "[Parameters]"
Print #1, "Install=1"
Print #1, "Quiet=0"
Print #1, "Use GPL Ghostcript=1"
Print #1, "AutoLaunch=0" ' = not run Acrobat each time
'---------------------------------------------------------------------
'- OUTPUT FILE & FOLDER FROM VARIABLES
Print #1, "OutPut File=" & OutputFile
Print #1, "User File=" & OutputFile ' same as OutPutFile
Print #1, "Launch=" & OutputFile ' same as OutPutFile
'---------------------------------------------------------------------
Close #1
'-------------------------------------------------------------------------
'- PRINT
ws.PrintOut ActivePrinter:="PDF995"
'-------------------------------------------------------------------------
'- WAIT UNTIL THE NEW OUTPUT FILE EXISTS (MAX 30 SECONDS)
CheckCount = 1
Do
Application.Wait Now + TimeValue("00:00:02") ' wait 2 seconds
CheckCount = CheckCount + 1
Loop While FileDateTime(OutputFile) <= MyFileDateTime _
And CheckCount < 15 ' 15 x 2 seconds = 30 seconds and give up
'----------------------------------------------------------------------
'- CHECK COUNTER
If CheckCount >= 15 Then
MsgBox ("Please check file " & OutputFile & " has been saved." & vbCr _
& "It took the full 30 seconds. The macro will continue.")
End If
'--------------------------------------------------------------------------
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,614
Messages
6,120,520
Members
448,968
Latest member
Ajax40

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