Run-time error 1004

josros60

Well-known Member
Joined
Jun 27, 2010
Messages
780
Office Version
  1. 365
Hi,

have the code below, sometimes get run-time error 1004 but is not all the time and with the error I also get this message "Document no saved. The document may be open, or an error may have been encountered when saving."

and highlight this line of the code:


VBA Code:
'Create the PDF
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFFile, _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=OpenPDFAfterCreating

Complete code:

VBA Code:
'Sub create_and_email_4pdf()
Sub create_and_email_4pdf() ' Author - Philip Treacy  ::   http://www.linkedin.com/in/philiptreacy
    ' http://www.MyOnlineTrainingHub.com/vba-to-create-pdf-from-excel-worksheet-then-email-it-with-outlook
    ' Date - 14 Oct 2013
    ' Create a PDF from the current sheet and email it as an attachment through Outlook
    
    
    Dim EmailSubject As String, EmailSignature As String
    Dim CurrentMonth As String, DestFolder As String, PDFFile As String
    Dim Email_To As String, Email_CC As String, Email_BCC As String, Email_body As String
    Dim OpenPDFAfterCreating As Boolean, AlwaysOverwritePDF As Boolean, DisplayEmail As Boolean
    Dim OverwritePDF As VbMsgBoxResult
    Dim OutlookApp As Object, OutlookMail As Object
    CurrentMonth = ""
    
    ActiveSheet.Shapes("Button 6").Delete
    ActiveSheet.Shapes("CommandButton1").Delete
    ActiveSheet.Shapes("Button 9").Delete
    ActiveSheet.Shapes("Button 12").Delete
    ActiveSheet.Shapes("Button 13").Delete
    Worksheets("STATEMENT").Range("I2").ClearComments
    Worksheets("STATEMENT").Range("I2").ClearContents
    Worksheets("STATEMENT").Range("I2").Interior.Color = xlNone

    ' *****************************************************
    ' *****     You Can Change These Variables    *********




    EmailSubject = ActiveSheet.Range("ACCOUNT") & "," & " " & "Account Reconciliation, Amount owing as today is " & Format(Range("J1").Value, "$#,##0.00;($#,##0.00)") 'Change this to change the subject of the email. The current month is added to end of subj line
    OpenPDFAfterCreating = True    'Change this if you want to open the PDF after creating it : TRUE or FALSE
    AlwaysOverwritePDF = False      'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
    DisplayEmail = True 'Change this if you don't want to display the email before sending.  Note, you must have a TO email address specified for this to work
    Email_To = ActiveSheet.Range("B3")   'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
    Email_CC = ActiveSheet.Range("C3")   'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
    Email_BCC = ""
    Email_body = "<p style='font-family:calibri;font-size:15'>" & "Hi" & " " & ActiveSheet.Range("A2") & "," & "<br>" & "<br>" & ActiveSheet.Range("X3") & " " & "<br>" & "<br>" '& "If you have any question regarding the attached statement, please let me know." & "<br>" & "<br>" & "<br>" & "<br>" & "Regards,"
    'Email_body = "" & "Hi" & ActiveSheet.Range("A2") & "," & "" & "" & ActiveSheet.Range("W3") & " " & "" & "" & "If you have any question regarding the attached statement, please let me know." & "" & "" & "" & "" & "Regards,"
    ' ******************************************************
    
    'Prompt for file destination
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = True Then
            'DestFolder = "C:\Documents and Settings\rossj1\Desktop\Excel Files\REMITTANCE\EXCEL_PDF" '.SelectedItems(1)
            DestFolder = ThisWorkbook.Path
        Else
            MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
            Exit Sub
        End If
    End With


    'Create new PDF file name including path and file extension
    CurrentMonth = Format(ActiveSheet.Range("H6").Value, "mm-dd-yyyy")
    PDFFile = DestFolder & Application.PathSeparator & ActiveSheet.Range("Reconciliation") & "_" & CurrentMonth & ".pdf"


    'If the PDF already exists
    If Len(Dir(PDFFile)) > 0 Then
        If AlwaysOverwritePDF = False Then
            OverwritePDF = MsgBox(PDFFile & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", vbYesNo + vbQuestion, "File Exists")
            On Error Resume Next
            'If you want to overwrite the file then delete the current one
            If OverwritePDF = vbYes Then
                Kill PDFFile
            Else
                MsgBox "OK then, if you don't overwrite the existing PDF, I can't continue." _
                    & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"
                Exit Sub
            End If
        Else
            On Error Resume Next
            Kill PDFFile
        End If
        If Err.Number <> 0 Then
            MsgBox "Unable to delete existing file.  Please make sure the file is not open or write protected." _
                    & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"
            Exit Sub
        End If
    End If


    'Create the PDF
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFFile, _
        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, OpenAfterPublish:=OpenPDFAfterCreating


    'Create an Outlook object and new mail message
    Set OutlookApp = CreateObject("Outlook.Application")
    Set OutlookMail = OutlookApp.CreateItem(0)
        
    'Display email and specify To, Subject, etc
    With OutlookMail
        .Display
        .To = Email_To
        .CC = Email_CC
        .BCC = Email_BCC
        .Subject = EmailSubject & ", " & CurrentMonth
        '.Body = Email_body
        .HTMLBody = Email_body & "" & .HTMLBody
                 .Attachments.Add PDFFile
               
        If DisplayEmail = False Then
        .Send
        End If
    End With
End Sub

don't know what it means document may be open.

thank you
 

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
Not sure but it could be that you are trying to create a file that already exists. If that's the case you better change this boolean by setting it to True.
VBA Code:
   AlwaysOverwritePDF = False      'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
 
Upvote 0
Hi

Changed to true as you can see below and still getting error 1004 and same message:

VBA Code:
'If the PDF already exists
If Len(Dir(PDFFile)) > 0 Then
If AlwaysOverwritePDF = True Then
OverwritePDF = MsgBox(PDFFile & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", vbYesNo + vbQuestion, "File Exists")
On Error Resume Next
'If you want to overwrite the file then delete the current one
If OverwritePDF = vbYes Then
Kill PDFFile
Else
MsgBox "OK then, if you don't overwrite the existing PDF, I can't continue." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"
Exit Sub
End If
Else
On Error Resume Next
Kill PDFFile
End If
If Err.Number <> 0 Then
MsgBox "Unable to delete existing file. Please make sure the file is not open or write protected." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"
Exit Sub
End If
End If

Thank you,
 
Upvote 0
My suggestion was to toggle the variable's assignment (near the top of your procedure). Instead, you've changed a comparison in which that variable was involved.
The person who wrote this code left some comments in it. Would recommend to read these comments.
Rich (BB code):
    OpenPDFAfterCreating = True         'Change this if you want to open the PDF after creating it : TRUE or FALSE
    AlwaysOverwritePDF = TRUE           'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
    DisplayEmail = True                 'Change this if you don't want to display the email before sending.  Note, you must have a TO email address specified for this to work
    Email_To = ActiveSheet.Range("B3")  'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
    Email_CC = ActiveSheet.Range("C3")  'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
 
Upvote 0
My suggestion was to toggle the variable's assignment (near the top of your procedure). Instead, you've changed a comparison in which that variable was involved.
The person who wrote this code left some comments in it. Would recommend to read these comments.
Rich (BB code):
    OpenPDFAfterCreating = True         'Change this if you want to open the PDF after creating it : TRUE or FALSE
    AlwaysOverwritePDF = TRUE           'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
    DisplayEmail = True                 'Change this if you don't want to display the email before sending.  Note, you must have a TO email address specified for this to work
    Email_To = ActiveSheet.Range("B3")  'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
    Email_CC = ActiveSheet.Range("C3")  'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
Sorry I am not that good in VBA would you please tell me changes need to make.

Thank you.
 
Upvote 0
I'm afraid I can't be clearer than my previous post; look especially at the red colored code line and compare that one to the code you provided in your post #1.
 
Upvote 0
Hi,
Made changes keep getting same error:

VBA Code:
EmailSubject = ActiveSheet.Range("ACCOUNT") & "," & " " & "Account Reconciliation, Amount owing as today is " & Format(Range("J1").Value, "$#,##0.00;($#,##0.00)") 'Change this to change the subject of the email. The current month is added to end of subj line
    OpenPDFAfterCreating = True    'Change this if you want to open the PDF after creating it : TRUE or FALSE
    [B][COLOR=rgb(184, 49, 47)]AlwaysOverwritePDF = True[/COLOR][/B]      'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
    DisplayEmail = True 'Change this if you don't want to display the email before sending.  Note, you must have a TO email address specified for this to work
    Email_To = ActiveSheet.Range("B3")   'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
    Email_CC = ActiveSheet.Range("C3")   'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
    Email_BCC = ""
    Email_body = "<p style='font-family:calibri;font-size:15'>" & "Hi" & " " & ActiveSheet.Range("A2") & "," & "<br>" & "<br>" & ActiveSheet.Range("X3") & " " & "<br>" & "<br>" '& "If you have any question regarding the attached statement, please let me know." & "<br>" & "<br>" & "<br>" & "<br>" & "Regards,"

Thank you
 
Upvote 0
don't know what it means document may be open.
This means that it is suspected that you want to save a PDF file with a certain file name, and that this certain name has already been assigned to an already existing file on disk, and that this file has been opened, usually in a suitable application, with PDF usually Acrobat Reader.
 
Upvote 0
This means that it is suspected that you want to save a PDF file with a certain file name, and that this certain name has already been assigned to an already existing file on disk, and that this file has been opened, usually in a suitable application, with PDF usually Acrobat Reader.
it's weird because there's no any open pdf file or saved pdf file.

thank you for your help.
 
Upvote 0

Forum statistics

Threads
1,214,823
Messages
6,121,780
Members
449,049
Latest member
greyangel23

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top