Excel: VBA to print to PDF - Run time error 1004

后端 未结 5 2099
谎友^
谎友^ 2021-01-07 10:32

I have tried using the following solution to print from Excel to PDF:

Excel 2013 Print to PDF in VBA

While the solution seems to have worked for other people

相关标签:
5条回答
  • 2021-01-07 10:32

    If the worksheet that you are exporting contains no data then the export fails. I found this solution on the MrExcel forum, where someone appears to have stumbled over the answer!

    0 讨论(0)
  • 2021-01-07 10:32

    OK, I just played with mine some more, and if I take the ".pdf" off the filename specification, I don't get the error 1004.

    0 讨论(0)
  • 2021-01-07 10:46

    I had to remove line breaks in my filename's variable using the clean function:

    xlName = Range("CustomerName").Value xlName = Application.WorksheetFunction.Clean(xlName)

    0 讨论(0)
  • 2021-01-07 10:48

    Another cause of this error is if the filename contains illegal characters such as:

    • < (less than)
    • > (greater than)
    • : (colon)
    • " (double quote)
    • / (forward slash)
    • \ (backslash)
    • | (vertical bar or pipe)
    • ? (question mark)
    • * (asterisk)

    See 'Naming conventions' here: https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file

    Solution: replace illegal characters with legal ones, such as '_'.

    0 讨论(0)
  • 2021-01-07 10:53

    So this is the working code now for Windows users (Mac OS might have to adjust file path):

    Sub Invoice_to_PDF()
    'Saves the invoice print area to a PDF file
    
    Dim fp As String
    Dim wb As Workbook
    Dim ws As Worksheet
    
    fp = "C:\Users\[username]\Desktop\NewInvoice.pdf"
    Set wb = ActiveWorkbook
    Set ws = Worksheets("Invoice")
    
    ws.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fp, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
    
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题