Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Change MS Excel Worksheet To PDF Format Using Access VBA

Posted on 2011-03-21
Medium Priority
Last Modified: 2012-06-22
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,

Question by:ref-IT
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2

Accepted Solution

KGNickl earned 1600 total points
ID: 35181351
LVL 37

Assisted Solution

TommySzalapski earned 400 total points
ID: 35182588
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).
LVL 37

Expert Comment

ID: 35182611
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).

Author Comment

ID: 35191001
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


Author Closing Comment

ID: 35191091
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 !!!


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
Microsoft has changed the look and feel of Azure AD and Microsoft account sign-in pages so that you will have a more unified look and feel when moving between the two interfaces.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

609 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question