Link to home
Start Free TrialLog in
Avatar of Mudasir Noorani
Mudasir NooraniFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Change MS Excel Worksheet To PDF Format Using Access VBA

Hello Experts,

I am writing an Access database where I have to program a module in VBA to convert an MS Excel Worksheet into a PDF Format and save it.

I have searched EE and I have obtained various sporadic results with many variations and possibilities including references which is quite confusing.

I guess what I am looking for is a straight link where I can download the reference dll's and/or object files and clean VBA code to change an Excel Worksheet into PDF Format.

All help and pointers are highly appreciated.

With Regards,

ref-IT
ASKER CERTIFIED SOLUTION
Avatar of KGNickl
KGNickl
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You may need to add a reference to the Excel library. Just click tools->references and go down to Microsoft Excel x.0 Object Library and click it. But you probably did that already. Replace ActiveSheet in the above code with whatever the variable is for the sheet (not the workbook).
Avatar of Mudasir Noorani

ASKER

Hello Experts,

Sorry for the delay in response. I had to sort the code out from an Access VBA Point of view in order to close the post for future references for anyone - besides other tasks that needed to be taken care of !!

@KGNickl: Thanks alot man for the URLs. The funny thing is, I did come across the Excel Guru Site when searching on Google and stumbled upon the Earyl Binding forum. However, I wasn't sure because of so many confusing directions, with Adobe Distiller, PrimoPDF, CutePDF and then the code - I was just not getting anywhere.

@TommySzalapski: Thanks for the post ... as you rightly mentioned, I did make a reference to the Excel x.0 Object Library. However, in the modified code below, I have used Late Binding.

The URLs posted by KGNickl give code snippets on how to convert to PDF from an Excel Worksheet VBA. I have examined the code, have made the necessary changes to amend it to suit Access VBA.

Both your help is highly appreciated especially KGNickl for the exact URLs.

Below is the Code For Access:



Private Sub ChangeToPDF()
On Error GoTo errHandler

Dim filePath As String
Dim fDialog As Office.FileDialog        'Eary Binding - Change this to Late Binding incase of error

Dim xlApp As Object
Dim xlWB As Object
Dim xlWS As Object

Dim pdfjob As Object
Dim sPDFName As String
Dim sPDFPath As String

'Dim lSheet As Long

'Initialise a fileDialog Picker to select the Excel file that needs to be converted
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
    .InitialFileName = "D:\"
    .AllowMultiSelect = False
    .Title = "Select file to change to pdf"
    .Filters.Add "All Files", "*.*"
    
    If .Show = True Then
        filePath = .SelectedItems(1)
    Else
        GoTo exitSub
    End If
End With


'Get the folder path and set the fileName
'Save PDF Files in folder called PDF Saved Files - Present in the same Directory as the Excel File
sPDFPath = Left(filePath, InStrRev(filePath, "\"))

'Create an Excel Object using Late Binding
'Obtain an already running instance of Excel
On Error Resume Next
Set xlApp = GetObject(, Excel.Application)

'If error exists, then there was no instance of Excel. Create a new instance
If Err <> 0 Then
    Set xlApp = CreateObject("Excel.Application")
End If
Err.Clear

With xlApp
    .Interactive = True
    
    Set xlWB = .Workbooks.Open(filePath, , False)
    Set xlWS = xlWB.Sheets(1)             
    xlWS.Activate
End With

If IsEmpty(xlWB.ActiveSheet.UsedRange) Then GoTo exitSub

Set pdfjob = CreateObject("PDFCreator.clsPDFCreator")

'Check if worksheet is empty and skip if so
If Not IsEmpty(xlWS.UsedRange) Then
    With pdfjob
        If .cStart("/NoProcessingAtStartup") = False Then
            MsgBox "Can't initialize PDFCreator.", vbCritical + _
            vbOKOnly, "PrtPDFCreator"
            GoTo exitSub
        End If
        
        '/// Change the output file name here! ///
        sPDFName = "testPDF.pdf" 
        .cOption("UseAutosave") = 1
        .cOption("UseAutosaveDirectory") = 1
        .cOption("AutosaveDirectory") = sPDFPath
        .cOption("AutosaveFilename") = sPDFName
        .cOption("AutosaveFormat") = 0    ' 0 = PDF
        .cClearCache
    End With

    'Print the document to PDF
    xlWS.PrintOut Copies:=1, ActivePrinter:="PDFCreator"
    
    'Wait until the print job has entered the print queue
    Do Until pdfjob.cCountOfPrintjobs = 1
        DoEvents
    Loop
    pdfjob.cPrinterStop = False

    'Wait until PDF creator is finished then release the objects
    Do Until pdfjob.cCountOfPrintjobs = 0
        DoEvents
    Loop
End If


pdfjob.cClose
Set pdfjob = Nothing

Set xlApp = Nothing
Set xlWB = Nothing
Set xlWS = Nothing

exitSub:
    Exit Sub
errHandler:
    MsgBox Err.Number & vbCrLf & vbCrLf & Err.Description
    Resume exitSub
End Sub

Open in new window

I have accepted KGNickl's solution for the posted URLs as they allowed me to refer to one website to draft the solution and TommySzalapski was quite handy as a guide to help formulate the Access VBA Solution by using Excel objects.

Kudos to both of you and thanks alot !!!

ref-IT