• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 971
  • Last Modified:

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,

  • 2
  • 2
2 Solutions
If you are using Excel 2007 then this code should work
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\temp\excel2pdftest.pdf", Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _

If that doesn't work, you just need this free download from MS then it will.
(Note, the code above is just from hitting 'record macro' and saving the sheet as a pdf. Most of those parameters can be left out and are the defaults. I left them in to make it easier to see what options you have).
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).
ref-ITAuthor Commented:
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)
        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

With xlApp
    .Interactive = True
    Set xlWB = .Workbooks.Open(filePath, , False)
    Set xlWS = xlWB.Sheets(1)             
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
    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
    pdfjob.cPrinterStop = False

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

Set pdfjob = Nothing

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

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

Open in new window

ref-ITAuthor Commented:
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 !!!

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now