Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Adding Save as PDF button ERROR

0

Hi,

I am very new to adding in macros to excel. I want to add in buttons to streamline back-end bookwork for the business to make it more efficient.

I watched the tutorial on here and copied in the same code using VBA. I tried to add in the code and a button to the sheet 'Invoice' however I get an error.

I am attaching my file here. I want the file name to save as what's in cell E10. However when I click on the button to save it, I get an error message and it highlights some of the code.

Any help appreciated so much!

Thanks in advance

Answer
Discuss

Discussion

Hello Soumbrero and welcome to the forum,

I downloaded your file and tested your code. The code attached to the purple button on the "Invoice" sheet is "CreatePDF". I copied your code (Module2) and made a new macro with a file path (newFilename) to my computer. The code ran fine - no error.

If you could give details about the error you are getting I (we) should be able to figure out what is triggering the error.

Cheers   :-)
WillieD24 (rep: 677) Mar 23, '25 at 11:39 pm
@Soumbrero - I've attempted to provide an Answer to your question- see below (but you may still need to provide the info requested above by WillieD24)

@Willie - good questions to a new user. Hopefuly we'll solve the issue between us.
John_Ru (rep: 6652) Mar 24, '25 at 11:57 am
@John
It looks like you've made a good assumption as to what error Soumbrero is encountering. You answer is also a good one (no surprise there). I am going to wait and see what/if additional info Soumbrero provides before I work on a solution.
Cheers   :-)
WillieD24 (rep: 677) Mar 24, '25 at 1:13 pm
@Willie - thanks. If my Answer isn't right for Soumbrero but he provides further information for you (as above), I'll step back so you can provide an Answer.
John_Ru (rep: 6652) Mar 24, '25 at 5:17 pm
Soumbrero - please react to the responses from Willie and me. 
John_Ru (rep: 6652) Mar 26, '25 at 6:30 am
@Soumbrero
Like John has said, we would like you to respond/answer our questions. For us to help you, you must help us.

What is the exact text of the error?
What line(s) of the macro trigger the error?
Hope to hear from you soon.
WillieD24 (rep: 677) Mar 26, '25 at 10:00 pm
Hello again, apologies for my delayed response. Actually I can't work out how to add any screenshots here...when I try to click the 'purple' button on the Invoice tab this is what happens:
1. I get an error message that says "error while printing" - the only option is to click 'ok'
2. When I click OK I am taken to the VBA screen and the error message as follows comes up: Run time error '1004':
Application-defined or object-defined error.

I can then click 'help', 'end' or 'debug'.
3. If I click debug, I then get a part of the text from the code highlighted in yellow.

At no point does a PDF come up. Thank you for your version that you modified and uploaded, I also tried that and the same thing happened as above.

Thanks for your help everyone!
Soumbrero Mar 27, '25 at 7:44 pm
Hello Soumbrero,

Note: to include a screenshot it would need to be pasted into a worksheet in an Excel file. Only Excel files can be uploaded.

Thanks for the additional info.
Item 1) I don't understand why you would get that error. The macro attached to your purple button is "CreatePDF()". This macro does not contain any code to print anything.
Item 2) "Run Time error 1004" can be triggered by several things.
Item 3) You mention that some of the code is highlighted in yellow but you failed to include that exact text which is highlighted in yellow. Also, is this highlighted text in the Module2 and the "CreatePDF()" macro or somewhere else?

Since I don't get any errors I need you to provide answers to Item 3. It is vitally important to know exactly what the yellow highlighted text is. Can you provide that info please.

Cheers   :-)
WillieD24 (rep: 677) Mar 27, '25 at 8:40 pm
Hi WillieD24, 
Thank you for your response.
I have attached another excel file to my original post "Invoice v2" which has the screenshots pasted into the second sheet.
I am not sure why I get the error about printing either.
If there is an alternate code that's easy (for a dummy like me), to insert a "save to pdf" button that would be great news.

Many thanks
Soumbrero Mar 27, '25 at 10:54 pm
Soumbrero. I can't see your second file "Invoice v2" in your Question- please  attach that so Willie (and I) can see the screenshot.
John_Ru (rep: 6652) Mar 28, '25 at 3:23 am
I am unsure why I can't upload it :( I have tried several times to add it to my original question. Never mind, I think trying to use code is proving too difficult for. Thank you for your time and help, I really appreciate it, but I'll stick with the more manual way of saving for now.
Cheers
Soumbrero Mar 28, '25 at 4:47 am
Soumbrero. Not sure why you can't  add a second file (but think that's happened in the past).

Using VBA code will save you a lot of time in the long run do should be worth a little effort... 

Why not add your screenshots in a new sheet of your original file, save that as v2 then edit your question, use the Add Files button to remove the first file and add the v2? 
John_Ru (rep: 6652) Mar 28, '25 at 6:21 am
Soumbrero- are you runing this on a Mac?

If not, does the folder 
C:\Test\Export\
exist? If so, which version of Excel are you using please?
John_Ru (rep: 6652) Mar 28, '25 at 8:48 am
Soumbrero- I'm pretty sure that all your problems arise from attempting to use Windows filepaths on a Mac. Please see Revision #1, 28 March 2025 at the end of my Answer below.
John_Ru (rep: 6652) Mar 28, '25 at 9:06 am
Hi again John_Ru,
Thanks so much for clarifying that. Yes it must have been because it's a Mac.
I have replaced with your revision (and my Mac username, I think).
Now, the first error that said "error while printing" does not appear (and neither do any of the others). Instead it comes up with a dialogue box that says "processing" for a split second then it disappears and I can not see that it has saved anywhere.
I do think this may be an issue to do with my Mac - I have had the same issue when trying to generally print files at work, that a dialogue box appears for a second, but nothing prints. I have to do then go a convoluded way by converting to pdf, downloading and then printing. I don't know if it's related but it's possible.
Soumbrero Mar 28, '25 at 10:27 pm
@Soumbrero

I am not familiar with coding for a Mac but you could use something like the following to log the invoice details to the Tracker sheet.
Dim TrackerNR As Long ' Next blank Row
TrackerNR = Sheets("Invoice Tracker").Range("A" & Rows.Count).End(xlUp).Row + 1
 
' Invoice Number
Sheets("Invoice Tracker").Cells(TrackerNR, 1) = Sheets("Invoice").Range("E10").Value
' Customer
Sheets("Invoice Tracker").Cells(TrackerNR, 2) = Sheets("Invoice").Range("B10").Value
' Invoice Amount
Sheets("Invoice Tracker").Cells(TrackerNR, 3) = Sheets("Invoice").Range("E33").Value
' Date Issued
Sheets("Invoice Tracker").Cells(TrackerNR, 4) = Sheets("Invoice").Range("E9").Value
' Date Paid - this entry is hard keyed
Sheets("Invoice Tracker").Cells(TrackerNR, 5) = "~ Enter Date Paid ~"
' Invoice Saved as PDF
Sheets("Invoice Tracker").Cells(TrackerNR, 6) = Sheets("Invoice").Range("E11").Value
' Date Invoice Mailed - this entry is hard keyed
Sheets("Invoice Tracker").Cells(TrackerNR, 7) = "~ Enter Date Emailed ~"

Hope this helps.

Cheers   :-)
WillieD24 (rep: 677) Mar 29, '25 at 1:24 am
@Soumbrero

After logging the details to the Tracker sheet you may want to sort the records. You could use something like the following:
    ' sort "Invoice Tracker" listings by invoive number
Range("A1:G" & TrackerNR).Select
    ActiveWorkbook.Worksheets("Invoice Tracker").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Invoice Tracker").Sort.SortFields.Add2 Key:=Range( _
        "A2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("Invoice Tracker").Sort
        .SetRange Range("A1:G" & TrackerNR)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    Range("A1").Select


Cheers   :-)
WillieD24 (rep: 677) Mar 29, '25 at 1:27 am
Soumbrero. You said above (on running the code on your Mac):

"....Instead it comes up with a dialogue box that says "processing" for a split second then it disappears and I can not see that it has saved anywhere. I do think this may be an issue to do with my Mac - I have had the same issue when trying to generally print files at work,"

As I said, I'm not really familiar with MacOS or the directory structure and can't fix printing problems on a Mac but (if you can't get someone to fix printing) you need to export the file to a known location on your Mac (you'll need to find one).

If that doesn't create a pdf file with the existing code, what happens if you change the export format as follows (change in bold) ? 
 
 
ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypeXPS, _
        FileName:=newFilename, _
        Quality:=xlQualityStandard, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

  which should create an XPS document instead  (though I read that it can't be read on a Mac without a third party program).


John_Ru (rep: 6652) Mar 29, '25 at 11:30 am
Add to Discussion

Answers

0

Soumbrero

Clicking the existing button on worksheet "Invoice" causes the sub CreatePDF to run.

That should create and open a pdf of the invoice BUT if you click it again without first closing the pdf, you'll get an error (since the code can't save when the same named file is open).and this line will appear in yellow (if you click Debug):

    ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=newFilename, _
        Quality:=xlQualityStandard, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True

If you halt the code, close the pdf and reclick, it should run again without problem.

Once you're confident the code works, you can get around that possible error by changing the end of the line as follows (in bold) so the pdf isn't opened:

    ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=newFilename, _
        Quality:=xlQualityStandard, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

If I may, I'd like to suggest a small improvement.... your line:

    ' Make a filename.
    newFilename = "C:\Test\Export\" & _
        ActiveSheet.Range("E10").Value & ".pdf"

produces filenames like "41.pdf".

It may be more meaningful to name the file like "Invoice #41.pdf" and further add the date of printing (since invoices sometimes need to be corrected).

To get file names like "Mar 24 2025 Invoice #41.pdf", I've changed the code in the attached file as follows (to not open the fuller named pdf but to give the user a message to say the file has been saved):

Sub CreatePDF()

' Create PDF

    ' Variables
    Dim newFilename As String

    ' Make a filename.
    newFilename = "C:\Test\Export\" & _
    Format(Date, "mmm dd yyyy") & _
    " Invoice #" & ActiveSheet.Range("E10").Value & ".pdf"


    ' Make the PDF.
    ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=newFilename, _
        Quality:=xlQualityStandard, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

    ' Tell the user
    MsgBox "Saved as " & newFilename


End Sub

Revision #1, 28 March 2025:

Soumbrero- I see from your later question that you are using a MacBook Pro, in which case the folder:

C:\Test\Export\

will NOT exist since MAC OS uses the forward slash (/) in filepaths, not back slash (\) as in Windows. (and you'll get the 1004 error).

In the file I provided, please change the line:

    ' Make a filename.
    newFilename = "C:\Test\Export\" & _
        ActiveSheet.Range("E10").Value & ".pdf"

to read a filepath that exists on your Mac, e.g.

    ' Make a filename.
    newFilename = "/Users/<< your Mac user name>>/Documents/" & _
        ActiveSheet.Range("E10").Value & ".pdf"
but replacing << your Mac user name>> to suit. (I don't have a Mac so could be wrong. Same approach should work with your original code.

Hope this helps and sorts your problem. If so, please remember to mark this Answer as Selected.

Discuss


Answer the Question

You must create an account to use the forum. Create an Account or Login